Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print first few lines of a text file in R

Tags:

r

tidyverse

I have a text file with no apparent tabular or other structure, for example with contents

some text on line 1
some more text on line 2
even more text on the third line
etc

What is the most elegant and R-like way to print out the first few (say 2) lines of text from this file to the console?

Option 1: readLines

readLines('file.txt', n=2)
# [1] "some text on line 1"      "some more text on line 2"

The n=2 option is useful, but I want the raw file contents, not the individual lines as elements of a vector.

Option 2: file.show

file.show('file.txt')
# some text on line 1
# some more text on line 2
# even more text on the third line
# etc

This output format is what I would like to see, but an option to limit the number of lines, like n=2 in readLines, is missing.

Option 3: system('head')

system('head -n2 file.txt')
# some text on line 1
# some more text on line 2

That's exactly the output I would like to get, but I'm not sure if this works on all platforms, and invoking an external command for such a simple task is a bit awkward.

One could combine the readLines solution with paste and cat to format the output, but this seems excessive. A simple command like file.head would be nice, or a n=2 argument in file.show, but neither exists. What is the most elegant and compact way to achieve this in R?

To clarify the goal here: This is for a write up of an R tutorial, where the narrative is something like "... we now have written our data to a new text file, so let's see if it worked by looking at the first couple of lines ...". At this point a simple and compact R expression, using base (update: or tidyverse) functions, to do exactly this would be very useful.

like image 841
sieste Avatar asked May 02 '18 10:05

sieste


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 print to a file in R?

Print values on R console or file using cat() or print()function can be used to print the argument. Print also returns the argument so it can be assigned. The “digits” argument specify the number of digits that should be displayed.


1 Answers

Use writeLines with readLines:

writeLines(readLines("file.txt", 2))

giving:

some text on line 1
some more text on line 2

This could alternately be written as the following pipeline. It gives the same output:

library(magrittr)

"file.txt" %>% readLines(2) %>% writeLines
like image 141
G. Grothendieck Avatar answered Oct 05 '22 07:10

G. Grothendieck