Load all R data files from a specific folder

I have a lot of Rdata files that I want to combine in one frame.

My files as an example:

file1.RData  
file2.RData  
file3.RData  

      

All data files are structured: datafile $ a and datafile $ b. From all the above files, I would like to load a variable $a

and add this and the already existing dataframe md

. My problem is not uploading files to the global environment, but processing the data in the RData file.

My code so far, which obviously doesn't work.

library(dplyr)
files <- list.files("correct directory", pattern="*.RData")

      

Returns the correct list of files.

I also know what I need lapply

over the function.

 lapply(files, myFun)

      

My problem is function. What I have at the moment:

myFun <- function(files) {
  load(files)
  df <- data.frame(datafile$a)
  md <- bind_rows(md, df)
}

      

The code above doesn't work, any idea how I can get this to work?

+3


source to share


1 answer


Try

 library(dplyr)
 bind_rows(lapply(files, myFun))
#    a
#1   1
#2   2
#3   3
#4   4
#5   5
#6   1
#7   2
#8   3
#9   4
#10  5
#11  6
#12  7
#13  8
#14  9
#15 10
#16 11
#17 12
#18 13
#19 14
#20 15

      

Where



 myFun <- function(files) {
    load(files)
    df <- data.frame(a= datafile$a)
 }

      

data

datafile <- data.frame(a=1:5, b=6:10)
save(datafile, file='file1.RData')

datafile <- data.frame(a=1:15, b=16:30)
save(datafile, file='file2.RData')
files <- list.files(pattern='file\\d+.RData')
files

      

+4


source







All Articles