Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read a text file in R line by line

Tags:

text

file-io

r

I would like to read a text file in R, line by line, using a for loop and with the length of the file. The problem is that it only prints character(0). This is the code:

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) 
like image 379
Layla Avatar asked Sep 27 '12 17:09

Layla


People also ask

How do I read a text file line by line in R?

Read Lines from a File in R Programming – readLines() Function. readLines() function in R Language reads text lines from an input file. The readLines() function is perfect for text files since it reads the text line by line and creates character objects for each of the lines.

How do I read a file in one line at a time in R?

By using R's pipe() command, and using shell commands to extract what we want, the full file is never loaded into R, and is read in line by line. It is this command that does all the work; it extracts one line from the desired file.

How do I read a text file into a string in R?

R can read any text file using readLines() or scan() . It is possible to specify the encoding of the imported text file with readLines() . The entire contents of the text file can be read into an R object (e.g., a character vector).

How do I read a text file into a list in R?

Read TEXT File in R using read. table() read. table() is a function from the R base package which is used to read text files where fields are separated by any delimiter.


1 Answers

You should take care with readLines(...) and big files. Reading all lines at memory can be risky. Below is a example of how to read file and process just one line at time:

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

Understand the risk of reading a line at memory too. Big files without line breaks can fill your memory too.

like image 134
dvd Avatar answered Oct 04 '22 02:10

dvd