merge() failed in the lapply loop

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")

Can you provide a reproducible example?

Hi Williaml,

I just rewrote my code to reproduce the issue. You just need to create a 'test' folder locally, then you can copy and paste my previous code in r. You will see the merge() doesn't work. I also tested by set i =0 in the beginning, and put i = i+ 1 in the middle to see if lapply() will add 1 each time finish the loop. And it didn't work.

For now I used for loop again to make it work.

If you can explain the difference between lapply and for loop. That will be great.

Thanks a lot.


This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.