How to append a whole dataframe to a CSV in R

前端 未结 3 1238
谎友^
谎友^ 2020-11-29 10:35

I can already append a row to a CSV using cat which makes that very easy:

  cat(\"my row, 1, 2, 3, 4\", \"mydf.csv\",sep=\"\\n\", append=TRU         


        
相关标签:
3条回答
  • 2020-11-29 10:54

    If you have enough memory, the most efficient way is to bind them all together then write to file:

    df <- cbind(df1, df2, df3)
    write.csv(df, "spam.csv")
    

    Otherwise, you can use the append argument in write.csv:

    dfs <- c(df1, df2, df3)
    for (df in dfs){
      write.csv(df, "eggs.csv", append = TRUE)
    }
    
    0 讨论(0)
  • 2020-11-29 11:01

    Another workaround (using cat) is that you transpose your data frame, then append a row containing only "\n" using rbind, then converting this data frame to a vector (it will have "\n" after every 'row') which will now show up in your csv file as a data frame.

    Below an example:

    df <- rbind(t(df),"\n")
    cat(c("",df),sep=",",append=TRUE)
    

    Note: my assumption is that you have opened a connection to a file using sink(filepath/filename.csv).

    0 讨论(0)
  • 2020-11-29 11:02

    Ok so I realised that append=T does work with write.table - but write.table needs the sep switch to be used so this works:

    write.table(myDF, "myDF.csv", sep = ",", col.names = !file.exists("myDF.csv"), append = T)
    
    0 讨论(0)
提交回复
热议问题