cboettig
cboettig

Reputation: 12677

Read in only the first n lines of a csv file in R

I really just want the header of a csv file in R, not sure what the best way to do that is.

I thought something like

read.csv(readLines("file.csv", n=3))

might work, but of course the output of readLines isn't a valid connection. I thought perhaps there's something clever to do with stdin here, but can't figure it out.

I'm looking for something better than just writing the readLines output to file and reading it back in, or manually implementing the header parsing that read.csv already does. (Of course those approaches would work but they seem a bit crude; more generally I'm trying to understand how best to redirect text as a connection).

Upvotes: 4

Views: 9802

Answers (1)

Dirk is no longer here
Dirk is no longer here

Reputation: 368221

There is an nrows= argument to read.table() which is passed through.

Example:

R> dim(read.csv("/usr/local/lib/R/site-library/fortunes/fortunes/fortunes.csv", 
+      nrows=3, header=TRUE, sep=";"))
[1] 3 5
R> 

(Pardon the sep=";" but I wanted to pick a file we'd both be likely to have ...)

Upvotes: 5

Related Questions