Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subset a vector of lists in R

Let's say I have a vector of lists:

library(tidyverse)

d <- tribble(
  ~x,
  c(10, 20, 64),
  c(22, 11),
  c(5, 9, 99),
  c(55, 67),
  c(76, 65)
)

How can I subset this vector such that, for example, I have have rows with lists having a length greater than 2? Here is my unsuccessful attempt using the tidyverse:

filter(d, length(x) > 2)
# A tibble: 5 x 1
  x        
  <list>   
1 <dbl [3]>
2 <dbl [2]>
3 <dbl [3]>
4 <dbl [2]>
5 <dbl [2]>
like image 372
Trent Avatar asked Dec 31 '22 09:12

Trent


2 Answers

It would be lengths as the 'x' is a list

library(dplyr)
d %>%
     filter(lengths(x) > 2)
like image 98
akrun Avatar answered Jan 09 '23 13:01

akrun


You can use subset() + lengths()

subset(d,lengths(x)>2)
like image 32
ThomasIsCoding Avatar answered Jan 09 '23 14:01

ThomasIsCoding