2016-09-19 72 views
0

我有許多文本文件包含僞格式爲[x1 y1] [x2 y2]的座標...我試圖將這些文件導入到R中以便我可以分析他們。然而,當我使用read.table導入它們時,它們變成一個含有兩個變量(x和y)的列表,每個值都是「[x」或「y」「,每個變量都有多個因子。我的問題是有沒有辦法導入或處理數據,以便它只是數值x值和y值的數據框?從R導入列表中刪除[和]

我已嘗試使用SUBSTR(),但得到
除去 「[」 和 「]」 字符 「錯誤的nchar(試驗[1,2]): '的nchar()' 需要的字符向量」
作爲錯誤消息。

+4

能否請您包括數據和/或代碼,將爲我們提供一個[重複的例子(HTTP:// stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example)? –

回答

2

讓我們假設這是輸入文件,它在你的工作目錄,並命名爲「fil.txt」

[5 6][7 8][9 10] 
[5 6][7 8][9 10] 
[5 6][7 8][9 10] 

然後你可以使用readLines,去掉「] [」對,並開始和結束從每行「[」和「]」,然後使用scan閱讀配對值:

x <-"[5 6][7 8][9 1 
[5 6][7 8][9 10] 
[5 6][7 8][9 10]" 

scan(text= gsub("(^\\[)|(\\]$)", "", gsub("\\]\\[", " ", readLines(textConnection(x)))), what = list(numeric(), numeric())) 
Read 9 records 
[[1]] 
[1] 5 7 9 5 7 9 5 7 9 

[[2]] 
[1] 6 8 10 6 8 10 6 8 10 

# I later realized the pattern could just be "\\[|\\]" and use a single gsub() 

> as.data.frame(.Last.value, col.names=c("x","y")) 
    x y 
1 5 6 
2 7 8 
3 9 10 
4 5 6 
5 7 8 
6 9 10 
7 5 6 
8 7 8 
9 9 10