有谁知道在R中裁剪多级列表的方法吗?对于列表中的每个元素,我有几个级别(例如属性“活着”、“年龄”、“颜色”)。我想将列表裁剪为只包含元素,例如x$color=="blue"
示例
set.seed(1)
ind <- vector(mode="list", 20)
for(i in seq(ind)){
ind[[i]]$alive <- 1
ind[[i]]$age <- 0
ind[[i]]$color <- c("blue", "red")[round(runif(1)+1)]
}
keep <- which(sapply(ind, function(x) x$color) == "blue")
keep
#[1] 1 2 5 10 11 12 14 16 19
ind[[keep]] # doesn't work
#Error in ind[[keep]] : recursive indexing failed at level 裁剪(或设置为NULL )对于具有单个级别的列表似乎是可能的,如下面的answer所示,但对我的多级列表不起作用。
发布于 2013-10-29 14:46:41
ind[keep]是你要找的东西。
来自?'[['
The most important distinction between ‘[’, ‘[[’ and ‘$’ is that the ‘[’ can select more than one element whereas the other two select a single element.
发布于 2013-10-29 14:49:48
或者,您可以使用Filter,并删除which步骤。
Filter(function(x) x$color == 'blue', ind)https://stackoverflow.com/questions/19661149
复制相似问题