如何在不丢失元素名称的情况下获取列表中元素的子集?

How do I get subset of the elements within a list without loosing the elements' name?

我有一个包含多个元素的列表(例如 A)。每个元素都具有相同的尺寸(例如 100 x 200)。我有一个向量 idx,长度为 100,行数与列表中的元素相同。我想创建一个新列表,它是列表 A 的子集,例如让 idx==1。我已经使用 lapply 并且它似乎可以工作但是我丢失了列表中的元素名称。你能建议一个更好的方法来实现这个目标吗?非常感谢

 # Generate a list A
 A = list()
 for (i in 1:26){
   A[[LETTERS[i]]] = matrix(runif(100*200,0,1),100,200)
 }
 # Generate a vector with 100 elements with integers between 1 and 5
 idx = sample(1:5, 100, replace=T)
 # Create subset list B from list A, where rows are idx==1
 B = lapply(1:26, function(x) A[[x]][idx==1,])
 # However, in list B, I have lost all the element names

我们需要遍历 list 并对其进行子集化

B1 <- lapply(A, function(x) x[idx==1,])

检查 OP 的结果是否相同

names(B) <- names(A)
identical(B, B1)
#[1] TRUE