简体   繁体   中英

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?

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.

You can use a command line utility like sed to remove trailing whitespace from a file:

sed -e :a -e 's/^.\\{1,77\\}$/ & /;ta'

Or, you could begin by writing a single row then using append .

An alternative in the similar vein of the answer by @Thomas, but with slightly less typing. Send output from write.csv to a character string ( capture.out ). Concatenate the string ( paste ) and separate the elements with linebreaks ( collapse = \\n ). Write to file with cat .

x <- capture.output(write.csv(df, row.names = FALSE, quote = FALSE))
cat(paste(x, collapse = "\n"), file = "df.csv") 

You may also use format_csv from package readr to create a character vector with line breaks ( \\n ). Remove the last end-of-line \\n with substr . Write to file with cat .

library(readr)
x <- format_csv(df)
cat(substr(x, 1, nchar(x) - 1), file = "df.csv")

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