I am facing a problem that I thought would be straightforward to solve but turned out to be far above my horizon. I guess I have a misconception stuck in my brain.
I have some data.frames which I imported from files. All of which have the exact same columns with the same names. Since they are quite many I wanted to automate the process of combining them into one data.frame using bind_rows.
files <- list.files(path = "/home/username/Documents/", pattern = ".txt")
batch.import <- function(filename) {
name <- unlist(strsplit(filename,"\\."))[1] # get rid of .txt
df <- read_tsv(filename)
colnames(df) <- c("name1", "name2", "name3", "name4")
assign(name, df, envir = .GlobalEnv)
}
map(files,batch.import)
dataframes <- unlist(strsplit(files,"\\."))[seq(1,length(unlist(strsplit(files,"\\."))),2)] # This produces a chr vector with all the data.frames I want to merge
First thing I obviously tried was:
combinedData <- bind_rows(dataframes)
Would have been too easy... I agree. Since it is a chr vector I actually understand, that this doesn't really refer to the data.frames but just to tries to do something with the text.
So I tried to use combinedData <- bind_rows(paste(dataframes))
which I thought could have done the job. But it wouldn't combine the data.frames either.
So I tried something more sophisticated, like a for loop (I also tried to use map()
usage here, which unfortunately I dont remember):
for (df in dataframes) {
if (exists("combinedData") {
combinedData <- bind_rows(combinedData, .data[[df]]) # Here I think is the error (if not already before) I also tried {{}}
} else {
cobinedData <- .data[[df]]
}
}
So from what I was reading until now I have to do something with {{}}
or .data[[]]
but this concept still didn't make it through to my synapses.
Any suggestions how I can use my chr-vector of data.frame names to combine the respective data.frames?
Thank you very much!
Michael