r - 合并列表中的 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
谢谢
解决方案
看起来你有矩阵列表。我们可以做的
#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"))))
推荐阅读
- mysql - 这个版本的 MariaDB 还不支持 'LIMIT & IN/ALL/ANY/SOME 子查询' - Multiple WHEREs and LIMITS
- python - 无法使用 igraph 函数“all_simple_paths”
- java - .NET 中的不可变列表:为什么允许添加和删除项目?
- python - 在python中绘制数字列表
- python - 如何根据列值使用 plotly 分配颜色值?
- flutter - 无法运行 Flutter_blue、BLE 插件的示例应用
- mysql - 无法卸载 mysql 损坏的 mysql / 安装新的 mysql
- r - 有没有办法向 R 包中的函数添加方法?
- excel - 如何根据条件从数组中复制值并将其粘贴到另一个工作表中?
- python - 如何从给定的列表范围生成所有可能的列表,这些列表将针对给定的输入总和