EN VI

Combine dataframes from nested list in R?

2024-03-15 08:00:08
How to Combine dataframes from nested list in R

I have a named list of data which contains named data frames.

mlst = list(test = list(df = data.frame(x = 1:10, y = 21:30), list(c(1:2))),
            test2 = list(df = data.frame(x = 1:10, y = 21:30), list(c(1:2))))
mlst$test$df
mlst$test2$df

The function do.call(rbind,mlst) do not work as this is not picking up only the data frames. How could I bind the rows of only the dataframes without a for loop?

Solution:

If the name of the data frame in each list is called "df" then you can extract those elements and row bind them like so:

library(purrr)

map(mlst, "df") |>
  list_rbind()

In base R you can do something similar:

lapply(mlst, `[[`, "df") |>
  do.call(rbind, args = _)
Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login