4

N行のcsvファイルがあります。各行はデータポイントに対応しています。このcsvファイルから事前に指定された行のセットを読み取る方法はありますか?

4

2 に答える 2

4

PythonやUnixシェルなどの別のツールを使用して必要な行を抽出する方が高速ですが、Rが最適な選択である場合:

file.in <- file('yourfile.txt', 'rt')
##file.header <- readLines(file.in,n=1) #do this if you are skipping a header
##change this to the lines that you want - line numbers must not decrease
ind.to.read <- c(10,15,20) 
##this is how many lines you want to skip in between lines you want
ind.to.skip <- c(ind.to.read[1],diff(ind.to.read)) - 1
# [1] 9 4 4 
##returns a list of data frames corresponding to rows
lines.to.keep <- lapply(ind.to.skip, function(x) { 
  readLines(file.in,n=x)
  read.table(file.in,nrow=1) 
}) 
small.df <- do.call(rbind,lines.to.keep) #put the data frames together
于 2012-12-11T22:55:28.417 に答える
4

skipおよびnrows引数をread.csv次のように指定できます。

skipinteger:データの読み取りを開始する前にスキップするデータファイルの行数。

nrowsinteger:読み込む最大行数。負の値やその他の無効な値は無視されます。

于 2012-12-11T21:09:25.943 に答える