temor
temor

Reputation: 1029

How to extract the first line from a text file?

I have a text file that I read like this:

file=read.table("file.txt",skip="1",sep="")

The first line of this text file contains information about the file then it is followed by the observations.

I want to extract the first line and write it out to a new text file.

Upvotes: 12

Views: 20646

Answers (2)

Santiago I. Hurtado
Santiago I. Hurtado

Reputation: 1123

Another way to do it is to read it with read.table() like this:

read.table(file = 'file.txt',header = F,nrows = 1)

This is a simple way to do it, and you can get your data separated into columns which makes it easier to work with.

Upvotes: 3

scoa
scoa

Reputation: 19867

To read the first line of a file, you can do:

con <- file("file.txt","r")
first_line <- readLines(con,n=1)
close(con)

To write it out, there are many options. Here is one:

cat(first_line,file="first_line.txt")

Upvotes: 24

Related Questions