当具有行名时,write.table将不需要的前导空列写入标头 [英] write.table writes unwanted leading empty column to header when has rownames

查看:199
本文介绍了当具有行名时,write.table将不需要的前导空列写入标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

检查此示例:

> a = matrix(1:9, nrow = 3, ncol = 3, dimnames = list(LETTERS[1:3], LETTERS[1:3]))
> a
  A B C
A 1 4 7
B 2 5 8
C 3 6 9

该表正确显示.有两种不同的方式将其写入文件...

the table displays correctly. There are two different ways of writing it to file...

write.csv(a, 'a.csv')给出预期结果:

"","A","B","C"
"A",1,4,7
"B",2,5,8
"C",3,6,9

write.table(a, 'a.txt')拧紧

"A" "B" "C"
"A" 1 4 7
"B" 2 5 8
"C" 3 6 9

的确,缺少一个空白的标签....这对于下游事物来说是一个痛苦. 这是错误还是功能? 有解决方法吗? (write.table(cbind(rownames(a), a), 'a.txt', row.names=FALSE除外)

indeed, an empty tab is missing.... which is a pain in the butt for downstream things. Is this a bug or a feature? Is there a workaround? (other than write.table(cbind(rownames(a), a), 'a.txt', row.names=FALSE)

干杯, 扬尼克

推荐答案

引用?write.table CSV文件部分:

默认情况下,没有列名 一列行名.如果col.names = NArow.names = TRUE为空白 列名称已添加,即 CSV文件使用的约定 通过电子表格读取.

By default there is no column name for a column of row names. If col.names = NA and row.names = TRUE a blank column name is added, which is the convention used for CSV files to be read by spreadsheets.

所以你必须做

write.table(a, 'a.txt', col.names=NA)

你会得到

"" "A" "B" "C"
"A" 1 4 7
"B" 2 5 8
"C" 3 6 9

这篇关于当具有行名时,write.table将不需要的前导空列写入标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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