Home > Enterprise >  how to subset a list of dataframes by its rowlength in R
how to subset a list of dataframes by its rowlength in R

Time:11-03

I have a list of dataframes and they all have the same column numbers. The difference is some of them have only a couple rows whereas others have a few hundred rows.

Now before my next step, I would like to filter this list and subset only the dataframes in the list have longer than n rows.

d1 <- data.frame(y1 = c(1, 2, 3), y2 = c(4, 5, 6), y3 = c(5, 5, 6))
d2 <- data.frame(y1 = c(3),y2 = c(4), y3 = c(5))
d3 <- data.frame(y1 = c(1, 2, 3), y2 = c(4, 5, 6), y3 = c(5, 5, 6))

my.list <- list(d1, d2,d3)

dataframe 1-3 all have 3 columns but d2 only has 1 row. How do I filter this list so I get my.list with only dataframes longer than 1 rows, aka d1 and d3?

CodePudding user response:

Try the code below

my.list[sapply(my.list,nrow)>1]

CodePudding user response:

Using purrr.

library(purrr)

keep(my.list, ~ nrow(.x) > 1)

CodePudding user response:

A base R solution:

Filter(function(x) nrow(x) > 1, my.list)
  • Related