I have the following script is working but failed to generate the output I expected.
I have three csv files for the lapply to loop, and it is able to generate the df dataframe. But I want to combine all 3 df from each csv file into one dataframe, that is why I use merge(). But the merge() doesn't work. Can anyone help me diagnose where I went wrong with my code?
Thanks in advance.
To reproduce my issue, you just need to create a ./test/ folder locally. Then the following code will generate 3 random csv files, and run the lapply.
# generate randome csv files
for (i in 1:3){
d1 <- data.frame(replicate(3, sample(0:2,4,rep=TRUE)))
colnames(d1) <- c("a", "b", "c")
path1 <- paste0( "./test/t",i,"1.csv")
write.csv(d1,path1, row.names = TRUE)
}
files <- list.files(path = "./test", pattern = ".csv", full.names = TRUE, recursive = FALSE)
X<- c(1,2,3,4)
df0 <- data.frame(X)
lapply(files, function(x){
df <- read.csv(x, header = TRUE)
df0 <- merge(df0,df, by = "X")
}
)