R 如何基于另一个列表对列表中的矩阵进行子集,该列表的值表示列号
我有一个矩阵列表(mat_list)。我想创建一个新列表,其中包含每个矩阵中选定的列子集。我有另一个数字列表(col_list),它指示要保留的列号。 示例数据集:R 如何基于另一个列表对列表中的矩阵进行子集,该列表的值表示列号,r,subset,lapply,R,Subset,Lapply,我有一个矩阵列表(mat_list)。我想创建一个新列表,其中包含每个矩阵中选定的列子集。我有另一个数字列表(col_list),它指示要保留的列号。 示例数据集: > mat_list <- list(structure(c(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L), .Dim = c(4L, 3L), .Dimnames = list(NULL, c("V1", "V2", "V3"))),structure(c(1L,
> mat_list <- list(structure(c(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L), .Dim = c(4L, 3L), .Dimnames = list(NULL, c("V1", "V2", "V3"))),structure(c(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L), .Dim = c(4L, 3L), .Dimnames = list(NULL, c("V1", "V2", "V3")))) ; names(mat_list) <- c("mat1","mat2")
> mat_list
$mat1
V1 V2 V3
[1,] 1 5 9
[2,] 2 6 10
[3,] 3 7 11
[4,] 4 8 12
$mat2
V1 V2 V3
[1,] 1 5 9
[2,] 2 6 10
[3,] 3 7 11
[4,] 4 8 12
> col_list <- list(structure(c(1,3)),structure(c(2,3))) ; names(col_list) <- c("var1","var2")
> col_list
$var1
[1] 1 3
$var2
[1] 2 3
我尝试使用lappy在所有矩阵中对这些列进行子集划分。我能做的最接近于
> lapply(mat_list,function(x) x[,col_list$var1])
$mat1
V1 V3
[1,] 1 9
[2,] 2 10
[3,] 3 11
[4,] 4 12
$mat2
V1 V3
[1,] 1 9
[2,] 2 10
[3,] 3 11
[4,] 4 12
这将使用col$var1中的值应用于mat_列表中的所有矩阵。但是我还没有能够成功地将这一点应用到col_list的所有(两个)元素上——例如,通过实现lappy到var_list,等等
lapply(mat_list,function(x) x[,lapply(var_list)])
我非常感谢您的意见。而不是
lappy
,在这种情况下mappy
非常适合:
mapply(function(x, y) x[, y], mat_list, col_list, SIMPLIFY = FALSE)
这也相当于
Map(function(x, y) x[, y], mat_list, col_list)
这两种方法都通过同时从mat_list
和col_list
获取相应的参数来应用指定的函数
正如您所注意到的,lappy
不起作用的原因是它只涉及一个变量。要使用lappy
则需要
lapply(seq_along(mat_list), function(i) mat_list[[i]][, col_list[[i]]])
好处:如果mat_list
包含数据帧而不是矩阵,那么使用
mapply(`[`, mat_list, col_list, SIMPLIFY = FALSE)
# or
Map(`[`, mat_list, col_list)
mapply(`[`, mat_list, col_list, SIMPLIFY = FALSE)
# or
Map(`[`, mat_list, col_list)