in R: save text file with different separators for each column?

天大地大妈咪最大 提交于 2019-12-13 00:45:05

问题


Is it possible in R to save a data frame (or data.table) into a textfile that contains different separators for various columns? For example: Column1[TAB]Column2[,]Column3 ?

[] indicate the separators, here a TAB and comma.


回答1:


The function write.table accepts only one separator.

MASS::write.matrix can do the trick:

require(MASS)
m <- matrix(1:12, ncol = 3)
write.matrix(m, file = "", sep = c("\\tab", ","), blocksize = 1)

returns

1\tab5,9
 2\tab 6,10
 3\tab 7,11
 4\tab 8,12

but as the documentation of this function does not say that multiple separators are allowed, it may be safer to do it by yourself, just in case the above has some side effects.

For example,

seps <- c("\\tab", ",", "\n")
apply(m, 1, function(x, seps) 
  cat(x, file = "", sep = seps, append = TRUE), seps = seps)

returns

1\tab5,9
2\tab6,10
3\tab7,11
4\tab8,12

Be aware that append is set to TRUE, so if the output file already exists it will be overwritten.



来源:https://stackoverflow.com/questions/24349527/in-r-save-text-file-with-different-separators-for-each-column

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!