abc_95
abc_95

Reputation: 179

Applying function to multiple .csv files

I have a files key (called "key") with two columns, like below:

ID newID
801deoi 1
802oieu 2
803qpoe 3
804intw 4

These participants complete questions before and after a distraction task, and I have replaced their alphanumeric ID code (on the left) with a new participant number (on the right).

Their .csv file is currently named after their ID, and I want to rename their scores after the distraction task (.csv file) with their new ID code (newID above) and with "_a" to signify that this is their score after the distraction task.

files <- list.files(path = 'data/', pattern = '*.csv', full.names = TRUE) 

key <- read.csv("key.csv")

Map(function(x, y) {
  tmp <- read.csv(files[x])
  tmp$participant <- paste0(y, "_a")
  write.csv(tmp, paste0(y, "_a"), row.names = FALSE, na = "")
}, key$ID, key$newID)

I have tried the code above, however the following error appears: "Error in file(file, "rt"): invalid 'description' argument". Can anyone help?

Upvotes: 0

Views: 213

Answers (1)

ngwalton
ngwalton

Reputation: 383

I would avoid using write.* in a function that should return something. Instead, I would just use a for loop. I don't have your data, so I can't test this, but here's how I might do this:

key <- read.csv("key.csv", as.is = TRUE)

for (id in key$ID) {
  pat <- paste0("*", id, "*")
  f <- list.files(path = 'data/', pattern = pat, full.names = TRUE)
  tmp <- read.csv(f)
  
  new_id <- key[key$ID == id, 'newID']
  tmp$participant <- paste0(new_id, "_a")
  
  write.csv(tmp, paste0('data/', new_id, "_a.csv"), row.names = FALSE, na = "")
}

Upvotes: 1

Related Questions