uow
uow

Reputation: 130

Write csv with different separators in same df in R

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

Upvotes: 0

Views: 881

Answers (2)

rdelrossi
rdelrossi

Reputation: 1154

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)

Upvotes: 1

Andre Wildberg
Andre Wildberg

Reputation: 19088

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)

Upvotes: 1

Related Questions