user3291268
user3291268

Reputation: 11

My "var" doesn't work well

all. I have a trouble about one of the most basic. Here is the problem;

> mean(1:10)
[1] 5.5

>sd(1:10)
[1] 3.02765

> var(1:10)
 [1] 0 0 0 0 0 0 0 0 0 0

> x<-data.frame(first=c(1,2),second=c(3,4))

> mean(x$first)
[1] 1.5

> sd(x$first)
[1] 0.7071068

> var(x$first)
[1] 0 0

> var(x)
     first second
[1,]     0      0
[2,]     0      0

Why R calculate variance for each cell? This is really inconvenient. I reinstalled R, but it did not fix the problem. Could you give me your advises?Please

Thank you. Kyosuke

Upvotes: 1

Views: 352

Answers (3)

IRTFM
IRTFM

Reputation: 263381

Do this:

ls(pattern='var')
rm(var)

It will get rid of the extraneous (and incorrect) function you have defined and is hanging around in the .Rdata image that is being loaded automatically. (It's a hidden file and it would not be wiped out by reinstalling.) If you define a function with the same name as a built-in function like var, it will mask the original function.

Upvotes: 1

Jilber Urbina
Jilber Urbina

Reputation: 61174

Use apply when you want to apply a function to either rows or cols

> apply(x, 2, var)
 first second 
   0.5    0.5 

Alternatively you can use sapply(x, var) if x is a data.frame

var(x$first) worked well for me

> var(x$first)
[1] 0.5

You can also use colVars function from matrixStats package

> #install.packages("matrixStats")
> library(matrixStats)
> colVars(x)
 first second 
   0.5    0.5 

See ?matrixStats for further details.

Upvotes: 0

Vincent
Vincent

Reputation: 5249

Your result looks strange. For your data var(x) and cov(x) should give:

       first second
first    0.5    0.5
second   0.5    0.5

Upvotes: 0

Related Questions