pfifas pfifas - 8 days ago 5
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(is.na(df[,"Y"])), 1]

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


The output in
test.csv
looks as follows

ID,1,2,3
X,a,b,c
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
NA
in the last line, there is another linebreak. When I pass
test.csv
to a Javascript chart on a website, however, the trailing linebreak causes trouble.

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

Answer

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)
close(zz)
foo
# [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.

Comments