简体   繁体   中英

is it possible to export an R dataframe to CSV with blank rows between groups?

I have a dataframe that I would like to export as a CSV, but I would like to insert a line after each group to make it easier to read if printed out.

I know this can be done in Excel after exporting ( How to automatically insert a blank row after a group of data ) and I have found at least 2 ways to insert a blank after the groups ( Insert a blank row after each group of data ) but they either (1) change the values of the groups and insert some dummy values in the blank rows to make it work or (2) don't readily export to csv. Is there a way to do this as part of the export. eg, as part of write.csv?

df <- tibble(
  x = c("a","a","a","b","c","c","c"),
  y = c(1,2,1,4,1,3,2)
)

ideally this would look like this in the csv:

a 1
a 2
a 1

b 4

c 1
c 3
c 2

An option would be to create a blank row (with add_row ) before the write.csv

library(tidyverse)
df %>%
    group_split(x) %>% 
    map_df(~ .x %>% 
               add_row(x = '', y = ''))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM