Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating sum of squared deviations in R

Tags:

r

statistics

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.

like image 355
JohnK Avatar asked Jan 27 '14 15:01

JohnK


People also ask

How do you find the squared value in R?

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.

How do you find the sum of deviation scores?

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?


2 Answers

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 )
like image 166
Dirk Eddelbuettel Avatar answered Oct 13 '22 14:10

Dirk Eddelbuettel


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:

enter image description here

like image 40
Sven Hohenstein Avatar answered Oct 13 '22 12:10

Sven Hohenstein