rnorouzian
rnorouzian

Reputation: 7517

Selective elimination from a list in R

I was wondering how I could eliminate the x elements from the second variable on (in this case, x[[2]] i.e., 0:90) in list x whose corresponding y is 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)

P.S. My goal is to possibly do this using lapply for any larger list.

Upvotes: 0

Views: 72

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388817

In this case, you could do

x[[2]][y[[2]] != 0]

to get your expected output.

However, as mentioned you have a larger list and want to do it for each one of them. In that case, we could use mapply

mapply(function(p, q) p[q != 0], x[2:length(x)], y[2:length(y)], SIMPLIFY = FALSE)

OR if we want to use lapply we could do

lapply(2:length(x), function(i) x[[i]][y[[i]] != 0])

If we want to keep the 1st element as it is we could do

c(list(x[[1]]), lapply(2:length(x), function(i) x[[i]][y[[i]] != 0]))

EDIT

To maintain the order we can rearrange the both x and y based on 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

Upvotes: 1

Related Questions