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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With