R write.table: 无效的 'col.names' 规范

R write.table: invalid 'col.names' specification

在包含大量 \t 符号的输入上使用 write.table 时,如何避免 invalid 'col.names' specification 错误?示例代码:

> x <- c("1\t119\t120\t1\t119\t120\tABC\tDEF\t0", "2\t558\t559\t2\t558\t559\tGHI\tJKL\t0", "3\t139\t141\t3\t139\t141\tMNO\tPQR\t0", "3\t139\t143\t3\t139\t143\tSTU\tVWX\t0")
> x
[1] "1\t119\t120\t1\t119\t120\tABC\tDEF\t0"
[2] "2\t558\t559\t2\t558\t559\tGHI\tJKL\t0"
[3] "3\t139\t141\t3\t139\t141\tMNO\tPQR\t0"
[4] "3\t139\t143\t3\t139\t143\tSTU\tVWX\t0"

> write.table(x, file = "file.txt", row.names = FALSE, col.names = c("A", "B", "C", "D", "E", "F", "G", "H", "I"))
Error in write.table(x, file = "uuu.txt", row.names = FALSE, col.names = c("A",  : 
  invalid 'col.names' specification

以下命令确实会产生输出 table,但两边仍保留双引号:

> write.table(x, file = "uuu.txt", row.names = FALSE, col.names = FALSE)

输出:

"1  119 120 1   119 120 ABC DEF 0"
"2  558 559 2   558 559 GHI JKL 0"
"3  139 141 3   139 141 MNO PQR 0"
"3  139 143 3   139 143 STU VWX 0"

相反,我想看到:

A   B   C   D   E   F   G   H   I
1   119 120 1   119 120 ABC DEF 0
2   558 559 2   558 559 GHI JKL 0
3   139 141 3   139 141 MNO PQR 0
3   139 143 3   139 143 STU VWX 0

我尝试了一些 strsplit(x, split = "\t") 的组合在调用 write.table 之前预处理输入,但是 运行 出现了同样的错误:invalid 'col.names' specification

如果数据不是表格形式,则不能将其写入表格形式。读入x,然后用

写入
write.table(read.table(text = x), 'file.txt', col.names = LETTERS[1:9], quote = FALSE)