如何在R中的data.table中按类别查找协方差矩阵

时间:2014-11-03 03:02:18

标签: r data.table covariance lapply sapply

假设我的数据包含3个类别。我想找到每个类别的协方差矩阵,并期望返回为数组。

set.seed(7)    
x <- rbind(cbind(rnorm(120,-1,0.1), rnorm(120,-0.5,0.1)),
               cbind(rnorm(120,-0.4,0.1), rnorm(120,0,0.1)),
               cbind(rnorm(120,.2,0.1), rnorm(120,0,0.1)))
lab <- c(rep(1, 120), rep(2, 120), rep(3, 120))
newx <- cbind(x, lab = lab)
s <- sapply(1:3, function(k){ var(newx[lab == k, -3]) })
dim(s) <- c(2,2,3)

返回,

, , 1

             [,1]         [,2]
[1,]  0.008880447 -0.001116058
[2,] -0.001116058  0.009229061

, , 2

             [,1]         [,2]
[1,]  0.012193536 -0.001217923
[2,] -0.001217923  0.009391710

, , 3

            [,1]        [,2]
[1,] 0.010752319 0.001231336
[2,] 0.001231336 0.008226595

我知道如何使用sapply,但如果我想使用data.table,我该怎么办呢?

我试过了:

library(data.table)
dt <- data.table(newx)
dt[,lapply(.SD, var), by = lab]

但它并没有像我预期的那样提供回报。

1 个答案:

答案 0 :(得分:1)

如果您需要将结果作为三维矩阵,那么显然这不是data.table。但是,您可以使用data.table进行计算。

library(data.table)
DT <- as.data.table(newx)
result <- DT[,var(.SD),by=lab]
result <- as.matrix(result$V1)
dim(result) <- c(2,2,3)
result
# , , 1
# 
#              [,1]         [,2]
# [1,]  0.008880447 -0.001116058
# [2,] -0.001116058  0.009229061
# 
# , , 2
# 
#              [,1]         [,2]
# [1,]  0.012193536 -0.001217923
# [2,] -0.001217923  0.009391710
# 
# , , 3
#
#             [,1]        [,2]
# [1,] 0.010752319 0.001231336
# [2,] 0.001231336 0.008226595