我有一个包含20个变量的数据框,每个变量有2个观察值。我用combn
计算了所有可能的变量对,现在对于每个观察和每对,我想计算平均值。可以使用2个变量的数据集的2个元素进行190种组合。
所以我有一个名为A
的数据框,包含20个变量(A1
- A20
)2个观察结果:
structure(list(A1 = c(-0.213231661750682, -0.221771671227651), A2 = c(-0.453268784292906, -0.411536539651889), A3 = c(-0.313590782870182, -0.32050845041221), A4 = c(-0.24068090024987, -0.237324659112412), A5 = c(-0.250518309189155, -0.243752386033467), A6 = c(-0.346513318287749, -0.310682137162937), A7 = c(-0.367893853843964, -0.389767604998544), A8 = c(-0.456036421130999, -0.476044422073483), A9 = c(-0.5235080360833, -0.424936488273877), A10 = c(-0.27421438645257, -0.254264546496442), A11 = c(-0.340599280820809, -0.378029798423225), A12 = c(-0.484056720613284, -0.497316258925064), A13 = c(-0.288377079820288, -0.279396742334153), A14 = c(-0.245523401712755, -0.248923757652515), A15 = c(-0.29225618208897, -0.253033910862832), A16 = c(-0.434525774496723, -0.515485159478136), A17 = c(-0.441791229146799, -0.44754900324085), A18 = c(-0.437452755366462, -0.405902999298872), A19 = c(-0.322178004640579, -0.321200331464843), A20 = c(-0.369930416907759, -0.376326662497664)), .Names = c("A1", "A2", "A3", "A4", "A5", "A6", "A7", "A8", "A9", "A10", "A11", "A12", "A13", "A14", "A15", "A16", "A17", "A18", "A19", "A20"), row.names = 1:2, class = "data.frame")
B <- combn(A, 2, simplify=FALSE)
例如,B的第一个元素是:
B[1]
A1 A2
-0.21 -0.45
-0.22 -0.41
我需要一个列表,返回190个向量,每个变量对应每个观察值的平均值,例如向量C
:
C
-0.33
-0.315
我尝试使用apply
,lapply
和sapply
,但我仍然收到错误消息(如dim(X) must have a positive length
)。 R将B
的每个元素存储为length=1
的列表,并且不能如此计算均值。我试图将每个元素转换为矩阵,但它将两个向量(A1
和A2
用于ex)放在matrix[1,1]
中。
我如何计算,最好使用函数apply
,因为我有很多数据?
答案 0 :(得分:2)
我们可以遍历list
&#39; B&#34;可以获得mean
sapply(B, rowMeans)
或者@ d.b.提到,请使用FUN
combn
参数
combn(A, 2, FUN = rowMeans)
set.seed(24)
A <- as.data.frame(matrix(sample(1:5, 5*20, replace = TRUE),
nrow = 5, ncol = 20, dimnames = list(NULL, paste0("A", 1:20))))