如何从使用write.table创建的CSV文件中删除尾随空格或换行符? [英] How to remove trailing blanks or linebreaks from CSV file created with write.table?
问题描述
我想将一个数据帧从R写入CSV文件。考虑下面的玩具示例
df df [
write.table(t(df),file =path to CSV / test.csv,sep =),col.names = F,sep =,,quote = F )
test.csv
如下
ID,1,2,3
X,a,b,c
Y, 1,2,NA
乍一看,这正是我需要的,但不能在上面的代码插入中看到的是,在最后一行中的 NA
之后,有另一个换行符。然而,当我将 test.csv
传递给网站上的Javascript图表时,后面的linebreak会导致麻烦。
有没有办法避免R中的最后一次换行?
这是一个有点复杂,但获得你想要的结果:
zz< - textConnection(foo,w)
/ pre>
write.table(t(df),file = zz,col.names = ,,quote = F)
close(zz)
foo
#[1]ID,1,2,3X,a,b,c 1,2,NA
cat(paste(foo,collapse ='\\\
'),file ='test.csv',sep ='')
你最终只能在前两个数据行之后有换行符的文件。
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 followsID,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 passtest.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.
这篇关于如何从使用write.table创建的CSV文件中删除尾随空格或换行符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!