Reputation: 3024
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
.
Upvotes: 2
Views: 3278
Reputation: 43334
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)
Upvotes: 3