dialektike
dialektike

Reputation: 421

variance operartion error in R

I have tried to operate to this simple problem in R

> ex <- c(1,2,3,4,5,6,7)
> mean(ex)
[1] 4
> var(ex)
[1] 4.666667
> sd(ex)
[1] 2.160247

But that is simple problem.
This is correct answer.

var(ex) = 4
sd(ex) = 2

What is problem in this case?

Upvotes: 1

Views: 84

Answers (1)

Andrea
Andrea

Reputation: 110

As already pointed out, R returns the sample variance. There is no built-in function to obtain the population variance as far as I know, but you can easily define it yourself multiplying the result by (n-1)/n:

 var.pop=function(x, y = NULL, na.rm = FALSE, use){
   n <- ifelse(is.null(dim(x)),length(x),dim(x)[1])
   return(var(x,y,na.rm,use)*(n-1)/n)
 }

This function will also calculate the population covariance. You can also define a similar version of the sd function or just call sqrt(var.pop(ex)).

Upvotes: 1

Related Questions