当var()应用于R中的数据帧行时会发生什么?

Mar*_*ars 2 r variance dataframe

新手R问题.很抱歉问:我确定它已经得到了解答,但很明显,它很难搜索到.我已经阅读了var(variance)的手册页,但我不明白.检查书籍,网页(好的,只有两本书).我等着有人指点我现有的答案......

> df
first second
1     1      3
2     2      5
3     3      7

> df[,2]
[1] 3 5 7

> var(df[,2])
[1] 4
Run Code Online (Sandbox Code Playgroud)

好的,到目前为止,这么好.

> df[1,]
  first second
1     1      3
> var(df[1,])
       first second
first     NA     NA
second    NA     NA
Run Code Online (Sandbox Code Playgroud)

咦?

提前致谢.!

bde*_*est 6

第一个问题是,当您从data.frame中选择行时,与从选择列时相比,您将获得不同的对象类:

df = data.frame(first=c(1, 2, 3), second=c(3, 5, 7))

class(df[, 2])
[1] "integer"

class(df[1, ])
[1] "data.frame"

# But you can explicitly convert with as.integer.
var(as.integer(df[1, ]))
# [1] 2
Run Code Online (Sandbox Code Playgroud)

第二个问题是var()对data.frame的处理方式完全不同.它将每列视为变量,并通过将每列与每个其他列进行比较来计算方差和协方差矩阵:

# Create a data frame with some random data.
dat = data.frame(first=rnorm(20), second=rnorm(20), third=rnorm(20))

var(dat)
#              first     second       third
# first   0.98363062 -0.2453755  0.04255154
# second -0.24537550  1.1177863 -0.16445768
# third   0.04255154 -0.1644577  0.58928970

var(dat$third)
# [1] 0.5892897

cov(dat$first, dat$second)
# [1] -0.2453755
Run Code Online (Sandbox Code Playgroud)