0

I'm trying to use a for loop on a function that takes the data file read by the loop, modifies it, and saves the result as a CSV file and can't figure out how to apply the loop so that each result would be saved as a separate CSV file.

Below are examples of my data frames:

df1 <- data.frame("age" = c(1.5, 5.5, 10), "group" = rep("A", 3))
df2 <- data.frame("age" = c(1, 5.5, 9, 15), "group" = rep("B", 4))
dffiles <- list(df1, df2)

Right now my code looks like this:

addone <- function(id,df){
new <- df[,1]+1
df$index <- id
name <- paste0("df",i)
assign(name, df)
write.csv(new, paste0("added", id, ".csv"))
}

for (i in 1:2){
  dffile <- dffiles[[i]]
  addone(i, dffile)
}

So the for loop is reading each original file, which would ideally each get a new index column and gets saved as a CSV file. There seems to be a problem with my loop though because I would get the correct file when I run individual lines in the function but my output from the loop doesn't include the index column. Can anyone point out which part in the loop I messed up?

M--
  • 25,431
  • 8
  • 61
  • 93
Jen
  • 331
  • 2
  • 11
  • 1
    I think this has been answered before: https://stackoverflow.com/questions/26707724/writing-multiple-data-frames-into-csv-files-using-r – Raphael K May 08 '19 at 02:21
  • Thanks for directing me to the post above! I think I understood how to create empty dataframes for each dataframe from the loop to fill in, now I'm having a different problem with properly saving the modified dataframe though (I edited the question). – Jen May 08 '19 at 17:50
  • 1
    These lines of code: `name <- paste0("df",i); assign(name, df)` is not working as expected and is unnecessary. The dataframe df is your desired value, so `write.csv(df, paste0("added", id, ".csv"))` is all you need. – Dave2e May 08 '19 at 18:47
  • @Dave2e Oh you're right, I didn't even realize, thanks for pointing that out! – Jen May 08 '19 at 18:55

1 Answers1

0

You need to create a new file name and then use the newly created name in the write.csv function.

Something like this should work:

#function takes an ID and creates the file name
func <- function(id, df) {
  new <- df[,1]+1
  write.csv(new, paste0("new", id, ".csv"))
} 


#the call to the function passes the identifier.
dffiles <- list(df1, df2)
for (i in 1:2){
  dffile <- dffiles[[i]]
  func(i, dffile)
}
Dave2e
  • 22,192
  • 18
  • 42
  • 50