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.
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")
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.
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