runixcatunix-head

How to read and print first head of a file in R?


I want to print a head of a file in R. I know how to use read.table and other input methods supported by R. I just want to know R alternatives to unix command cat or head that reads in a file and print some of them.

Thank you,

SangChul


Solution

  • read.table() takes an nrows argument for just this purpose:

    read.table(header=TRUE, text="
        a b
        1 2
        3 4
        ", nrows=1)
    #   a b
    # 1 1 2
    

    If you are instead reading in (possibly less structured) files with readLines(), you can use its n argument instead:

    readLines(textConnection("a b
    1 2 3 4 some other things
    last"), n=1)
    # [1] "a b"