简体   繁体   中英

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

How do I avoid the invalid 'col.names' specification error when using write.table on input that has plenty of \\t symbols in it? Sample code:

> 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

The following command does produce an output table, but still retains double quotes on both sides:

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

Output:

"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"

Instead, I would like to see:

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

I've tried some combinations of strsplit(x, split = "\\t") to preprocess the input before invoking write.table , but ran into the same error: invalid 'col.names' specification .

You can't write data into tabular form if it's not in tabular form already. Read in x , and then write it with

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM