Reputation: 9017
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.
Upvotes: 5
Views: 6451
Reputation: 269481
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
Upvotes: 8