Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

question from:https://stackoverflow.com/questions/65829410/sum-all-x-values-and-subtract-by-their-mean

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
284 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...