Home > Software design >  Subsetting from a list of dataframes in R
Subsetting from a list of dataframes in R

Time:11-01

I have a list of dataframes:

df1 <- data.frame(c(1:5), c(6:10))
df2 <- data.frame(c(1:7))
df3 <- data.frame(c(1:5), c("a", "b", "c", "d", "e"))
my_list <- list(df1, df2, df3)

From my_list, I want to extract the data frames which have only 2 columns (df1 and df3), and put them in a new list.

CodePudding user response:

Maybe you can try lengths

> my_list[lengths(my_list) == 2]
[[1]]
  c.1.5. c.6.10.
1      1       6
2      2       7
3      3       8
4      4       9
5      5      10

[[2]]
  c.1.5. c..a....b....c....d....e..
1      1                          a
2      2                          b
3      3                          c
4      4                          d
5      5                          e

CodePudding user response:

It's also possible to subset using lapply and a logical condition (sapply will also work):

my_list[lapply(my_list, ncol) == 2]
[[1]]
  c.1.5. c.6.10.
1      1       6
2      2       7
3      3       8
4      4       9
5      5      10

[[2]]
  c.1.5. c..a....b....c....d....e..
1      1                          a
2      2                          b
3      3                          c
4      4                          d
5      5                          e

CodePudding user response:

We could use keep from purrr package with the condition:

library(purrr)
my_list %>% keep(~ ncol(.x) == 2)
[[1]]
  c.1.5. c.6.10.
1      1       6
2      2       7
3      3       8
4      4       9
5      5      10

[[2]]
  c.1.5. c..a....b....c....d....e..
1      1                          a
2      2                          b
3      3                          c
4      4                          d
5      5                          e
  • Related