Unify files in a data frame in r

1

I try to unify files (whose names are 001.csv , ..., 332.csv ) with the following for:

files.together<- function(directory,id=1:332) {
        files<-list.files(path = directory,full.names = T)
        values<-numeric()
        for(i in id){
                data<-read.csv(files[i])
                values<-rbind(values,data)
        }
        write.csv(x = values,file = "data.csv")
        data<-read.csv(file.path(getwd(),"data.csv"),header = T)
}

It works very well, except the last line, where what I'm trying to do is to automatically load the new unified file that has been created with the for

    
asked by David Alejandro 30.09.2016 в 20:23
source

1 answer

1

You can avoid using a for loop using functions of the apply family in the following way:

filenames <- list.files(path = directory, pattern = "[0-3][0-9]{2}.csv")
df <- do.call(rbind,lapply(filenames, read.csv))
write.csv(df, file = "unificado.csv", row.names = FALSE, quote = FALSE)

In the case that you want to pass parameters to the function read.csv would be in the following way (assuming that file csv is separated by ; )

df <- do.call(rbind, lapply(filenames, read.csv, sep = ";"))
    
answered by 12.10.2016 в 23:07