Search code examples
rsumstandard-deviationhardcode

Sum all x-values and subtract by their mean


I am trying to hard code the formula for standard deviation in R (yes, I know there is a function to do this). This is what I have so far.

x = c(1, 6, 2, 7, ... #shortened for clarity
n = length(x)
xBar <- mean(x)
...
StDev = sqrt((sum(x - xBar)) / (n-1))

This outputs zero. I am less experienced in R, but I believe my problem is with sum(x - xBar). How can I take the summation of all x-values minus the mean? Thanks!

I would prefer not to write a new function.


Solution

  • You're missing a ^2. This is your same code with the right formula.

    x <- c(1, 6, 2, 7)
    n <- length(x)
    xBar <- mean(x)
    ...
    StDev <- sqrt(sum((x - xBar)^2) / (n - 1))
    

    And here you can see it gives the same output as sd().

    StDev 
    [1] 2.94392
    sd(x)
    [1] 2.94392