Home > Back-end >  How to choose specific elements from multiple lists in a simple way?
How to choose specific elements from multiple lists in a simple way?

Time:11-05

I have these two lists (let's imagine we have hundreds of lists) :

l1 = list(c(1,2,3),c(12))
l2 = list(data.frame(x=c(1,2,3)),c(4,5))

and I wish to choose only the second element from each list. How to do so ? thanks.

CodePudding user response:

Try

f1 <- function(lstobj)
{
   lapply(lstobj, \(x) if(is.data.frame(x)) x[[1]][2] else x[2])
}

If it is to extract the second list element

f1 <- function(lstobj, ind)
     lstobj[[ind]]
}
f1(l1)
f1(l2)

CodePudding user response:

To select the second element of each list, you can use lapply with "[[" and 2, like this:

l1 = list(c(1,2,3),c(12))
l2 = list(data.frame(x=c(1,2,3)),c(4,5))

lists <- list(l1, l2)
lapply(lists, "[[", 2)
#> [[1]]
#> [1] 12
#> 
#> [[2]]
#> [1] 4 5

Created on 2022-11-04 with reprex v2.0.2

  • Related