我在 R 中有一个 df 列表,比如说
list.data<-list(df1=df1,df2=df2)
所有 df
具有相同的行数和相同的列数
我有一个由 TRUE/FALSE 值组成的矩阵 m
。假设 df 是
[,1] [,2]
[1,] -1.8526984 -1.3359316
[2,] -0.9391172 -1.4453051
[3,] 0.2793443 -1.0223621
[4,] 2.0174213 -1.1734235
[5,] 0.2100461 -0.1261543
而 df2 是
[,1] [,2]
[1,] -1.8526984 0.1956987
[2,] 0.1737456 -1.4453051
[3,] 1.7133539 0.4562011
[4,] -0.6132369 -0.3532976
[5,] -0.5008479 1.5729352
我的矩阵m
是
[,1] [,2]
[1,] FALSE TRUE
[2,] TRUE FALSE
[3,] TRUE TRUE
[4,] TRUE TRUE
[5,] TRUE TRUE
我想将 list.data
对象中包含的 df
合并到一个数据帧中,仅取第 i 行和第 j 列中标记为的元素的平均值矩阵 m
为 TRUE,同时保持数据帧的其他元素不变。
例如:最终数据帧应该是一个 5 x 2 矩阵,例如,(2,1) 元素应该是 df2_(2,1) 和 df1_(2,1) 之间的平均值,因为 m_(2,1)是真的。 1,1 元素应为 df1_(1,1) 或 df_2(1,1),因为 m(1,1) 为 FALSE
谢谢
最佳答案
看起来你有矩阵列表。我们能做到
#Create a matrix to hold the result
result <- matrix(0, ncol = ncol(m), nrow = nrow(m))
#Find indices to calculate mean
inds <- which(m)
#Indices for which the values is to be taken as it is
non_inds <- which(!m)
#Subset the indices from list of matrices and take their mean
result[inds] <- rowMeans(sapply(list.data, `[`, inds))
#Subset the indices from first list as it is
result[non_inds] <- list.data[[1]][non_inds]
result
# [,1] [,2]
#[1,] -1.8526984 -0.5701164
#[2,] -0.3826858 -1.4453051
#[3,] 0.9963491 -0.2830805
#[4,] 0.7020922 -0.7633606
#[5,] -0.1454009 0.7233905
数据
list.data <- list(df1 = structure(c(-1.8526984, -0.9391172, 0.2793443,
2.0174213,
0.2100461, -1.3359316, -1.4453051, -1.0223621, -1.1734235, -0.1261543
), .Dim = c(5L, 2L), .Dimnames = list(NULL, c("V1", "V2"))),
df2 = structure(c(-1.8526984, 0.1737456, 1.7133539, -0.6132369,
-0.5008479, 0.1956987, -1.4453051, 0.4562011, -0.3532976,
1.5729352), .Dim = c(5L, 2L), .Dimnames = list(NULL, c("V1",
"V2"))))
关于r - 结合列表中的 df 并仅对特定值求平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55676150/