在 R 中:为每列保存具有不同分隔符的文本文件? [英] in R: save text file with different separators for each column?

查看:75
本文介绍了在 R 中:为每列保存具有不同分隔符的文本文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在 R 中将数据框(或 data.table)保存到包含不同列的不同分隔符的文本文件中?例如:Column1[TAB]Column2[,]Column3 ?

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.

推荐答案

write.table 函数只接受一个分隔符.

The function write.table accepts only one separator.

MASS::write.matrix 可以解决这个问题:

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

返回

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.

例如

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

返回

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

请注意,append 设置为 TRUE,因此如果输出文件已存在,它将被覆盖.

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

这篇关于在 R 中:为每列保存具有不同分隔符的文本文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆