Reputation: 184
I am trying to write a for loop in R with a list of dataframes and path names For some reason,the second dataframe is the only one that exports. Any help would be greatly appreciated.
df1 <- data.frame(num = sample(1:10, 6, replace = TRUE), letter = sample(LETTERS[1:2], 6, replace =
TRUE))
df2 <- data.frame(num = sample(150:160, 6, replace = TRUE), letter = sample(LETTERS[1:2], 6, replace
= TRUE))
list_dfs <- list(df1,df2)
paths <- c("C:\\Export\\file1.csv","C:\\Export\\file2.csv")
for (i in 1:length(list_dfs)) {
for (f in 1:length(paths)) {
write.csv(list_dfs[i], file = paths[f], row.names = FALSE)
}
}
Upvotes: 2
Views: 1291
Reputation: 736
This should work:
for (i in 1:length(list_dfs)) {
write.csv(list_dfs[i], file = paths[i], row.names = FALSE)
}
}
The code you provided was writing list_dfs[1]
to path[1]
and then path[2]
. Followed by list_dfs[2]
to path[1]
and then path[2]
, resulting in list_dfs[2]
being written to path[1]
and path[2]
.
If you want to include a check that list_dfs
and paths
are the same length you could do:
for (i in 1:length(list_dfs)) {
if(length(list_dfs) != length(path)){stop("mismatch in number of data frames and paths")}
write.csv(list_dfs[i], file = paths[i], row.names = FALSE)
}
}
Ultimately though, if you want to export each data frame once, you only need one for()
loop.
I hope this helps!
Upvotes: 2