0

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に示すように、単一レベルのリストではクロッピングまたは への設定が可能ですが、マルチレベル リストでは機能しません。

4

2 に答える 2

2

または、 を使用してステップFilterを切り取ることもできます。which

Filter(function(x) x$color == 'blue', ind)
于 2013-10-29T14:49:48.283 に答える
2

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-29T14:46:41.453 に答える