简体   繁体   中英

How to merge multiple .RData using for loop in R?

I have multiple .RData files in a folder. All samples have 10 rows and 5 columns

sample 1.RData
sample 2.RData
sample 3.RData
sample 4.RData
sample 5.RData
sample 6.RData
sample 7.RData
sample 8.RData

I can load them using the following code

seed.no=c(1:8)
    for ( ss in seed.no){
      #Load .RData
      sample=load.Rdata2(filename = paste0("sample",ss,".RData"))
       sample_all=rbind(sample)
    }

I would like to merge all data files row-wise as

  sample_all= rbind(sample 1.RData, sample 2.RData, sample 3.RData,sample 4.RData,sample 5.RData,sample 6.RData,sample 7.RData ,sample 8.RData).

sample_all should have 80 rows and 5 columsn .

Unfortunately sample_all=rbind(sample) is not giving me the expected results inside the loop.

Any help is appreciated .

We can use lapply to loop over the files namess, load the data and then rbind with do.call

out <- do.call(rbind, lapply(paste0("sample", 1:8, ".RData"), load.Rdata2))

With a for loop, we can do the same thing

out1 <- data.frame()
for(rdata in paste0("sample", 1:8, ".RData")) {
       out1 <- rbind(out1, load.Rdata2(rdata))
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM