Search code examples
rloopstidyversepurrrrdata

Read dataframe from list in multiple RData files


I have a bunch of RData files (1.RData, 2.RData... 100.RData) all containing three list elements, "X", "Y" and "Z". Within list Z is a dataframe that I want to read into to R in a nested tibble.

My go-to method for reading multiple files is obviously no good:

library(tidyverse)

my_files <-
  list.files(path = "path_to_files",
             pattern = ".RData",
             recursive = TRUE,
             full.names = TRUE)

# how the hell am I suppose to read the Z$df into my nested tibble?

df <-
  tibble(filename = my_files) %>%
  mutate(file_contents = map(
    my_files,
    ~ load(.) 
  ))

This yields a tibble with a list column where each list contains the character values "X", "Y" and "Z" without all the data nested within each list.

Is it possible to read a nested dataframe from many RData files into a nested tibble?

(This is my first question on here, so I tried my best to communicate my question satisfactorily.)


Solution

  • Loop through filenames, load, then extract the dataframe, (not tested):

    dfList <- lapply(my_files, function(i){
      load(i)
      Z$df
      })