Jacob H
Jacob H

Reputation: 4513

Sub-setting elements of a list in R

Assume that this is my list

a <- list(c(1,2,4))
a[[2]] <- c(2,10,3,2,7)
a[[3]] <- c(2, 2, 14, 5)

How do I subset this list to exclude all the 2's. How do I obtain the following:

[[1]]
[1] 1 4

[[2]]
[1] 10  3  7

[[3]]
[1] 14  5

My current solution:

for(j in seq(1, length(a))){
  a[[j]] <- a[[j]][a[[j]] != 2]
}

However, this approach feels a bit unnatural. How would I do the same thing with a function from the apply family?

Thanks!

Upvotes: 0

Views: 48

Answers (2)

Pierre L
Pierre L

Reputation: 28461

lapply(a, function(x) x[x != 2])
#[[1]]
#[1] 1 4
#
#[[2]]
#[1] 10  3  7
#
#[[3]]
#[1] 14  5

Using lapply you can apply the subset to each vector in the list. The subset used is, x[x != 2].

Upvotes: 3

akrun
akrun

Reputation: 887571

Or use setdiff by looping over the list with lapply

lapply(a, setdiff, 2)
#[[1]]
#[1] 1 4

#[[2]]
#[1] 10  3  7

#[[3]]
#[1] 14  5

Upvotes: 1

Related Questions