dalitmil
dalitmil

Reputation: 41

merge data nasted dataframes in R

I have several DFs. Each of them is res csv file of one participant form my exp. Some of the csv have 48 variables. Others have in addition to these identical variables 6 more variable (53 variables). However, If I try to merge them like this:

flist <- list.files(path="my path", pattern = ".csv", full.names = TRUE)
Merge<-plyr::ldply(flist, read_csv) #Merge all files

the merging is done by the columns orders and not by the variable name. Therefore in one column in my big combine DF I get data form different variables.

So I tried different strategy: uploading my files as separate DFs:

data_files <- list.files("my_path")  # Identify file names
data_files  

for(i in 1:length(data_files)) {                              # Head of for-loop
  assign(paste0("data", i),                                   # Read and store data frames
         read_csv(paste0("my_path/",
                          data_files[i])))
}

Then I tried to merge them by this script:

listDF <- names(which(unlist(eapply(.GlobalEnv,is.data.frame)))) #list of my DFs 
listDF

library(plyr)
MergeDF<-do.call('rbind.fill', listDF)

But I'm still stuck.

Upvotes: 1

Views: 48

Answers (1)

akrun
akrun

Reputation: 886938

We may use map_dfr

library(readr)
library(purrr)
map_dfr(setNames(flist, flist), read_csv, .id = "id")

Upvotes: 1

Related Questions