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

Categories

0 votes
283 views
in Technique[技术] by (71.8m points)

r - 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.

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

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

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...