Jane
Jane

Reputation: 395

Keeping only data.frames in list of list

My list looks something like that and I would like to remove those type=character so that I can use rbindlist.

enter image description here

I tried the following, but is_df became empty 'List of 0'.

is_df <- sapply(lst2, is.data.frame)

finaldf <- do.call("rbind.fill", lst2[is_df])

Upvotes: 2

Views: 290

Answers (3)

akrun
akrun

Reputation: 886948

We can use keep with bind_rows

library(purrr)
library(dplyr)
keep(lst2, is.data.frame) %>% 
      bind_rows

Upvotes: 0

Ronak Shah
Ronak Shah

Reputation: 388817

You can use Filter to keep only dataframes in the list and use dplyr::bind_rows/data.table::rbindlist to combine the dataframes into one.

finaldf <- dplyr::bind_rows(Filter(is.data.frame, lst2))

Upvotes: 0

jay.sf
jay.sf

Reputation: 72633

Just try the normal rbind function.

is_df <- sapply(lst2, is.data.frame)
finaldf <- do.call(rbind, lst2[is_df])
#           X1         X2          X3          X4
# 1  0.1037688 -0.4290532 -0.04030139  1.58023365
# 2 -2.3746286  0.9738965 -0.21019970 -0.09594634
# 3 -1.6957693  2.0731743 -0.59138986  0.59526342
# 4  2.0508162 -0.2134047  0.72179608 -0.66588172
# 5  1.7916146 -0.5836235  0.88100016  0.62486794
# 6 -1.8532820 -0.2537533  1.33270460 -0.57808697
# 7 -0.4378837  0.8352826  0.20929615 -0.12018995
# 8  0.4057582 -1.0262310  0.46144461  0.21372192
# 9 -1.9495696 -0.1062967 -0.81992543 -1.18818584

Data:

lst2 <- c(list(1:3, letters[1:4]), replicate(3, data.frame(matrix(rnorm(12), 3, 4)), simplify=F))

Upvotes: 1

Related Questions