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?