f.a
f.a

Reputation: 101

how to write multiple dataframe to a single csv file in a loop in R?

I would like to write a multiple dataframe "neighbours_dataframe" in a single CSV file :

I use this line to write the multiple dataframe to multiple file :

for(i in 1:vcount(karate)){
write.csv(neighbours_dataframe[[i]], file = as.character(V(karate3)$name[i]),row.names=FALSE)}

if I use this code:

for(i in 1:vcount(karate)){
write.csv(neighbours_dataframe[[i]], file = "karate3.csv",row.names=FALSE)}

this would give me just the last dataframe in the csv file :

I was wondering , How could I have a single CSV file which have all the dataframe in the way that the column header of the first dataframe just written to the csv file and all other data frame copied in a consecutive manner ?

thank you in advance

Upvotes: 1

Views: 5917

Answers (1)

Richie Cotton
Richie Cotton

Reputation: 121077

Two methods; the first is likely to be a little faster if neighbours_dataframe is a long list (though I haven't tested this).

Method 1: Convert the list of data frames to a single data frame first

As suggested by jbaums.

library(dplyr)
neighbours_dataframe_all <- rbind_all(neighbours_dataframe)
write.csv(neighbours_dataframe_all, "karate3.csv", row.names = FALSE)

Method 2: use a loop, appending

As suggested by Neal Fultz.

for(i in seq_along(neighbours_dataframe))
{
  write.table(
    neighbours_dataframe[[i]], 
    "karate3.csv", 
    append    = i > 1, 
    sep       = ",", 
    row.names = FALSE,
    col.names = i == 1
  )
}

Upvotes: 2

Related Questions