pfifas pfifas - 2 months ago 19
R Question

How to remove trailing blanks or linebreaks from CSV file created with write.table?

I want to write a data frame from R into a CSV file. Consider the following toy example

df <- data.frame(ID = c(1,2,3), X = c("a", "b", "c"), Y = c(1,2,NA))
df[which([,"Y"])), 1]

write.table(t(df), file = "path to CSV/test.csv", sep = ""), col.names=F, sep=",", quote=F)

The output in
looks as follows

Y, 1, 2,NA

At first glance, this is exactly as I need it, BUT what cannot be seen in the code insertion above is that after the
in the last line, there is another linebreak. When I pass
to a Javascript chart on a website, however, the trailing linebreak causes trouble.

Is there a way to avoid this final linebreak within R?


This is a little convoluted, but obtains your desired result:

zz <- textConnection("foo", "w")
write.table(t(df), file = zz, col.names=F, sep=",", quote=F)
# [1] "ID,1,2,3"   "X,a,b,c"    "Y, 1, 2,NA"
cat(paste(foo, collapse='\n'), file = 'test.csv', sep='')

You should end up with a file that has newline character after only the first two data rows.