2

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

> 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

以下命令确实会生成一个输出表,但仍会在两边保留双引号:

> 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

4

1 回答 1

3

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

write.table(read.table(text = x), 'file.txt', col.names = LETTERS[1:9], quote = FALSE)
于 2016-05-01T23:39:36.477 回答