在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多个列和行的数据集。有什么有效的方法来做到这一点吗?
发布于 2014-07-04 11:15:42
您可以使用连接并以块方式处理文件:
复制您的数据:
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"https://stackoverflow.com/questions/24572252
复制相似问题