Select only elements of a list containing tables with two columns in R

Viewed 222

I have a list containing 10000 elements, each element contains a table with different amount of columns, an example list (with less elements) is shown below. Is there a way to only select the elements with two columns in an extra list but only showing the numbers and not the characters (as in the example [[1]])?

$`1`

  a   g 
 41 498 

$`2`

  c   t  g
 40 499  1

$`3`

  a   c   g   t 
 28  36 466   9 

$`4`

  t 
539 

Expected output would be:

$`1`

41 498

Do you know any solution?

3 Answers

We can use lengths to create a logical vector to subset the list, then loop over the subset list and unname or convert to a vector with as.vector or unlist (if it is a data.frame)

lapply(lst1[lengths(lst1) == 2], unname)
#$`1`
#[1]  41 498

If these are data.frame in a list

lapply(lst1[sapply(lst1, ncol) == 2], unlist, use.names = FALSE)

data

lst1 <- list(`1` = c(a = 41, g = 498), `2` = c(c = 40, t = 499, g = 1
), `3` = c(a = 28, c = 36, g = 466, t = 9), `4` = c(t = 539))

Here I'm using lapply to find which lengths are equal to 2, then indexing.

let L be your list

L[lapply(L,length) == 2]

Maybe you can try

  • subset with lengths
> subset(lst,lengths(lst)==2)
$`1`
  a   g
 41 498
  • Filter
> Filter(function(x) length(x)==2,lst)
$`1`
  a   g
 41 498

Data

> dput(lst)
list(`1` = c(a = 41, g = 498), `2` = c(c = 40, t = 499, g = 1
), `3` = c(a = 28, c = 36, g = 466, t = 9), `4` = c(t = 539))
Related