r - 从R中的列表中选择性消除
问题描述
我想知道如何从对应的列表中(在这种情况下,即 )上的第二个变量中x
消除元素?x[[2]]
0:90
x
y
0
x = list(0:5, 0:90) # from the second variable on, in this list, eliminate elements whose
# corresponding `y` is `0` ?
y = lapply(list(dbinom(x[[1]], 5, .9), dpois(x[[2]], 50)), round, digits = 4)
PS我的目标是可能使用lapply
任何更大的列表来做到这一点。
解决方案
在这种情况下,你可以做
x[[2]][y[[2]] != 0]
获得预期的输出。
但是,如前所述,您有一个更大的列表,并且希望为每个列表执行此操作。在这种情况下,我们可以使用mapply
mapply(function(p, q) p[q != 0], x[2:length(x)], y[2:length(y)], SIMPLIFY = FALSE)
或者如果我们想使用lapply
我们可以做
lapply(2:length(x), function(i) x[[i]][y[[i]] != 0])
如果我们想保持第一个元素不变,我们可以这样做
c(list(x[[1]]), lapply(2:length(x), function(i) x[[i]][y[[i]] != 0]))
编辑
为了保持顺序,我们可以重新排列两者x
并y
基于smallest_max
get_new_list <- function(x, y) {
smallest_max <- which.min(sapply(x, max))
new_x <- c(x[smallest_max], x[-smallest_max])
new_y <- c(y[smallest_max], y[-smallest_max])
c(new_x[1], lapply(2:length(new_x), function(i) new_x[[i]][new_y[[i]] != 0]))
}
x = list(0:5, 0:40)
y = lapply(list(dbinom(x[[1]], 5, .9), dpois(x[[2]], 50)), round, digits = 4)
get_new_list(x, y)
#[[1]]
#[1] 0 1 2 3 4 5
#[[2]]
#[1] 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
x = list(0:40, 0:5)
y = lapply(list(dpois(x[[1]], 50), dbinom(x[[2]], 5, .9)), round, digits = 4)
get_new_list(x, y)
#[[1]]
#[1] 0 1 2 3 4 5
#[[2]]
#[1] 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40