M.Stadler
M.Stadler

Reputation: 1

R merge in loop

I have a lot of csv files that I want to read and then merge with a larger file (each file merged individually). So I wrote this function to read the files (works):

read <- function(x) {
    read.csv(paste("StringCount_Length=", x, ".csv", sep = ""), header=TRUE, sep=",")
}

Now I want to loop through the files, read and merge them. However, the merge does not work giving me this error message:

Error in fix.by(by.x, x) : 'by' must specify a uniquely valid column

I do not get the error if I put a specific file in the merge command so my mistake must be there but I can't quite see where I went wrong. Would be grateful for any help or advice!

for (x in c(2:5)) { 
  assign(paste("data", x, sep=""), read(x))
  assign(paste("data_total_",x, sep=""), merge(paste("data", x, sep=""),    data_old, by="Subject"))
}

Upvotes: 0

Views: 1420

Answers (1)

RAVI PIPALIYA
RAVI PIPALIYA

Reputation: 21

Similar to the assign function where you are assigning an object to a name string, you need to use the get function where you invoke an object using a name string of the object instead of directly using the object name.

The code below should do the job where we encapsulate the paste function with the get function.

e.g. For x = 2, data2 data frame will be accessed with get("data2") function call

for (x in c(2:5)) { 
  assign(paste("data", x, sep=""), read(x))
  assign(paste("data_total_",x, sep=""), 
  merge(get(paste("data", x, sep="")),    data_old, by="Subject"))
    }

Upvotes: 1

Related Questions