2014-07-04 14 views
3

R有沒有方便的方法從固定寬度的數據文件中讀取特定列(或多列)?例如。該文件看起來像這樣:如何從R中的大固定寬度文件的特定列中讀取R

10010100100002000000 
00010010000001000000 
10010000001002000000 

說,我有興趣柱15.在我讀與read.fwf並作爲整個數據的那一刻寬度爲1的向量與總數的長度列:

data <- read.fwf("demo.asc", widths=rep(1,20)) 
data[,14] 
[1] 2 1 2 

這可以很好地工作,但不會擴展到具有100,000個列和行的數據集。有沒有任何有效的方法來做到這一點?

+0

請問[這個問題](http:// stac koverflow.com/questions/19706927/read-only-n-th-column-of-a-text-file-which-has-no-header-with-r-and-sqldf)或[this discussion](http: //r.789695.n4.nabble.com/is-there-a-way-to-read-a-specific-column-from-a-txt-file-td881689.html)幫助你? – A5C1D2H2I1M1N2O1R2T1

+0

您是否在第二個「read.fwf」示例中檢查過使用'width'參數? – Henrik

+1

@Henrik負的寬度值?是的,我已經看到了,但是這會對多個列很複雜(先訂購,然後計算跳過等) – furukama

回答

2

您可以使用連接和處理塊中的文件:使用連接塊

dat <-"10010100100002000000 
00010010000001000000 
10010000001002000000" 

過程:

# Define a connection 
con = textConnection(dat) 


# Do the block update 
linesPerUpdate <- 2 
result <- character() 
repeat { 
    line <- readLines(con, linesPerUpdate) 
    result <- c(result, substr(line, start=14, stop=14)) 
    if (length(line) < linesPerUpdate) break 
} 

# Close the connection 
close(con) 

結果:

複製數據

result 
[1] "2" "1" "2" 
+0

謝謝!這很好。 – furukama

相關問題