How can I calculate the sum of squared deviations(from the mean) of a vector?
I tried using the command
sum(x-mean(x))^2
but unfortunately what this returns is -1.998401e-15 which cannot be right. Is there a subtle operator, like a parenthesis, that I am missing here perhaps?
Thanks.
To calculate square in R, use the ^ operator or multiply the input value by itself, and you will get the square of the input value.
First, determine n, which is the number of data values. Then, subtract the mean from each individual score to find the individual deviations. Then, square the individual deviations. Then, find the sum of the squares of the deviations...can you see why we squared them before adding the values?
It may well be correct. -2.0 to the power of 10^15 means it is essentially zero. But as Justin just noted in the comment, you have
(sum (x - mean(x) )^2
when you probably meant:
sum( (x - mean(x) )^2 )
You can also use another way to calculate the sum of squared deviations:
x <- 1:10 #an example vector
# the 'classic' approach
sum( (x - mean(x) )^2 )
# [1] 82.5
# based on the variance
var(x) * (length(x) - 1)
#[1] 82.5
The latter works because var(x) = (x - mean(x))^2) / (length(x) - 1)
. This is the sample variance:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With