2012-09-27 10 views
25

Rの行を1行ずつ読み込み、forループとファイルの長さを使ってテキストファイルを読みたいと思います。問題は、文字(0)のみを出力することです。これはコードです:行ごとにR行のテキストファイルを読む

fileName="up_down.txt" 
con=file(fileName,open="r") 
line=readLines(con) 
long=length(line) 
for (i in 1:long){ 
    linn=readLines(con,1) 
    print(linn) 
} 
close(con) 
+8

問題は、ファイル全体を( 'line = readLines(con)')読み込み、ループ内でファイルを読み続けることです。その時点で、読むことは何も残っていません。 –

+0

[多分大きいかもしれない]ファイルから一度に1行だけをロードする方法を探しているのであれば、[現在受け付けている回答](http://stackoverflow.com/a/12627356/1067114)はあなたの問題を解決していません問題。代わりに、ファイルの内容を1行ずつ処理したい場合は、ロードする方法にかかわらず、問題をより適切に定式化する必要があります。 –

答えて

25

forループを備えたソリューションです。重要なことは、forループからreadLinesへの1回の呼び出しが必要なので、何度も繰り返し呼び出されることはありません。ここにあります:

fileName <- "up_down.txt" 
conn <- file(fileName,open="r") 
linn <-readLines(conn) 
for (i in 1:length(linn)){ 
    print(linn[i]) 
} 
close(conn) 
+2

ベクター全体を印刷しているので、forループは一切必要ありません。ちょうど 'print(linn)'で十分です。 –

+1

非常に良い答えです。 Rでは " - "は通常 "="の代わりに使用されます。 – Ryan

+2

30ギガバイトのファイルがあればどうなりますか? – Chris

31

はちょうどあなたのファイルにreadLinesを使用します。

R> res <- readLines(system.file("DESCRIPTION", package="MASS")) 
R> length(res) 
[1] 27 
R> res 
[1] "Package: MASS"                 
[2] "Priority: recommended"               
[3] "Version: 7.3-18"                 
[4] "Date: 2012-05-28"                
[5] "Revision: $Rev: 3167 $"               
[6] "Depends: R (>= 2.14.0), grDevices, graphics, stats, utils"      
[7] "Suggests: lattice, nlme, nnet, survival"           
[8] "[email protected]: c(person(\"Brian\", \"Ripley\", role = c(\"aut\", \"cre\", \"cph\")," 
[9] "  email = \"[email protected]\"), person(\"Kurt\", \"Hornik\", role" 
[10] "  = \"trl\", comment = \"partial port ca 1998\"), person(\"Albrecht\"," 
[11] "  \"Gebhardt\", role = \"trl\", comment = \"partial port ca 1998\"),"  
[12] "  person(\"David\", \"Firth\", role = \"ctb\"))"       
[13] "Description: Functions and datasets to support Venables and Ripley,"    
[14] "  'Modern Applied Statistics with S' (4th edition, 2002)."     
[15] "Title: Support Functions and Datasets for Venables and Ripley's MASS"   
[16] "License: GPL-2 | GPL-3"               
[17] "URL: http://www.stats.ox.ac.uk/pub/MASS4/"          
[18] "LazyData: yes"                 
[19] "Packaged: 2012-05-28 08:47:38 UTC; ripley"          
[20] "Author: Brian Ripley [aut, cre, cph], Kurt Hornik [trl] (partial port"   
[21] "  ca 1998), Albrecht Gebhardt [trl] (partial port ca 1998), David"   
[22] "  Firth [ctb]"                
[23] "Maintainer: Brian Ripley <[email protected]>"        
[24] "Repository: CRAN"                
[25] "Date/Publication: 2012-05-28 08:53:03"           
[26] "Built: R 2.15.1; x86_64-pc-mingw32; 2012-06-22 14:16:09 UTC; windows"   
[27] "Archs: i386, x64"                
R> 

これまで全体のマニュアル献身があります...ここで

+0

私はreadLinesを使用していますが、なぜ私はそのエラーが出るのかわかりません。 – Layla

+0

マニュアル全体が捧げられていると言えば、どのマニュアルであるか教えてください。 –

57

あなたはreadLines(...)と大きなファイルに注意してください。メモリ上のすべての行を読むことは危険です。以下は、一度に一つだけの行のファイルやプロセスを読み取る方法の例です:

processFile = function(filepath) { 
    con = file(filepath, "r") 
    while (TRUE) { 
    line = readLines(con, n = 1) 
    if (length(line) == 0) { 
     break 
    } 
    print(line) 
    } 

    close(con) 
} 

もメモリにラインを読んでのリスクを理解します。改行のない大きなファイルもメモリをいっぱいにすることがあります。

+3

これは実際には受け入れられる回答です。他の人は大きなファイルの問題にぶつかります。 – theduke

+0

これは、大きなファイルを1行ずつ解析する正しい方法であることが示唆されています。他の答えは、すべての行をメモリに読み込んだ後、そのオブジェクトをメモリにループします。これはこれとはまったく異なります。 –

1

私は別の行に異なるデータ型を持っている私の要求を満たすためにファイルを1行ずつ読み込むコードを書いてください。記事:read-line-by-line-of-a-file-in-rdetermining-number-of-linesrecords。そして、それは大きなファイルのためのより良い解決策でなければならない、と私は思う。私のRバージョン(3.3.2)。

con = file("pathtotargetfile", "r") 
readsizeof<-2 # read size for one step to caculate number of lines in file 
nooflines<-0  # number of lines 
while((linesread<-length(readLines(con,readsizeof)))>0) # calculate number of lines. Also a better solution for big file 
    nooflines<-nooflines+linesread 

con = file("pathtotargetfile", "r") # open file again to variable con, since the cursor have went to the end of the file after caculating number of lines 
typelist = list(0,'c',0,'c',0,0,'c',0) # a list to specific the lines data type, which means the first line has same type with 0 (e.g. numeric)and second line has same type with 'c' (e.g. character). This meet my demand. 
for(i in 1:nooflines) { 
    tmp <- scan(file=con, nlines=1, what=typelist[[i]], quiet=TRUE) 
    print(is.vector(tmp)) 
    print(tmp) 
} 
close(con) 
関連する問題