Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

csv

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

like image 229
cboettig Avatar asked Oct 26 '25 10:10

cboettig


1 Answers

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

like image 103
Dirk Eddelbuettel Avatar answered Oct 27 '25 23:10

Dirk Eddelbuettel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!