2016-05-01 53 views
0

如何在使用write.table的輸入上有大量\t符號時避免出現invalid 'col.names' specification錯誤?示例代碼:R write.table:無效的'col.names'規範

> 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

回答

2

如果數據不是表格形式,則無法將數據寫入表格形式。請閱讀x,然後用

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