1

I have a number of RData files in which a specific information is stored.

for (filename in c("file1", "file2", "file3")) {
  
  a = tibble(letters = sample(LETTERS, 10),
              numbers = sample(1:100, 10))
  
  save(a, file = paste0("tmp/", filename, ".RData")) }

I now want to read in the data stored in these files in a nested tibble for further analyses.

However, I don't know how to load the data stored in these files in a way that it ends up in a tibble.

ndf <- tibble(path = list.files("tmp", full.names = TRUE),
              file = basename(path), 
              a = purrr::map(path, function(path) {
                load(path) # does not do what I want
              }))

I then want to continue with my analysis like e.g.

analysis <- ndf %>% 
  mutate(mean = purrr::map_dbl(a, function(a) mean(a$numbers)))

The problem is that load is intended to store retrieved objects in the environment, and does not return the list of retrieved objects or simliarly. Therefore, another solution seems to be necessary.

mzuba
  • 1,226
  • 1
  • 16
  • 33

1 Answers1

1

Since load() invisibly returns the name of the object(s) loaded, you can simply use get() to refer to that specific object:

ndf <- tibble(path = list.files("tmp", full.names = TRUE),
              file = basename(path), 
              a = purrr::map(path, function(path) {
                load(path) %>% get
              }))
mzuba
  • 1,226
  • 1
  • 16
  • 33