Home > OS >  Write csv with different separators in same df in R
Write csv with different separators in same df in R

Time:02-08

I have a dataframe in R and I need to export it as .csv with "," separator to the column names and ";" separator to the rest of the dataframe (all the data rows).

So I need something like this:

name_col1,name_col2,name_col3
v1;v2;v3
v4;v5;v6

CodePudding user response:

With readr you can use write_delim() to output a file with comma-separated column names then call it a second time, without column names, and in append mode.

library(read)

mtcars[0, ] %>% 
  write_delim(file = "test.dat",delim = ',', col_names = TRUE)

mtcars %>% 
  write_delim(file = "test.dat",delim = ';', col_names = FALSE, append = TRUE)

CodePudding user response:

Simply use 2 write.tables

d
  name_col1 name_col2 name_col3
1        v1        v2        v3
2        v4        v5        v6

write.table(t(colnames(d)), file="d.dat", sep=",", col.names=F, row.names=F)
write.table(d, file="d.dat", sep=";", col.names=F, row.names=F, append=T)
  •  Tags:  
  • Related