首页 > 解决方案 > 合并列表中的 df 并仅对特定值进行平均

问题描述

我在 R 中有一个 df 列表,比如说

list.data<-list(df1=df1,df2=df2)

所有df具有相同数量的行和相同数量的列我有一个m由 TRUE/FALSE 值组成的矩阵。假设 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

我想将df我的list.data对象中包含的内容合并到一个数据帧中,仅取矩阵标记为 TRUE 的第 i 行和第 j 列中的元素的平均值,m同时保持数据帧的其他元素不变。

例如:最终数据帧应该是 5 x 2 矩阵,例如 (2,1) 元素应该是 df2_(2,1) 和 df1_(2,1) 之间的平均值,因为 m_(2,1) 为 TRUE。1,1 元素应该是 df1_(1,1) 或 df_2(1,1) 因为 m(1,1) 是 FALSE

谢谢

标签: rlistdataframe

解决方案


看起来你有矩阵列表。我们可以做的

#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"))))

推荐阅读