[R] [newbie] read row from file into vector

Duncan Murdoch murdoch.duncan at gmail.com
Thu Dec 29 22:45:45 CET 2011


On 11-12-29 3:51 PM, Tom Roche wrote:
>
> summary: how to read a row (not column) from a file into a vector (not a data frame)?
>
> details:
>
> I'm using
>
> $ lsb_release -ds
> Linux Mint Debian Edition
> $ uname -rv
> 3.0.0-1-amd64 #1 SMP Sun Jul 24 02:24:44 UTC 2011
> $ R --version
> R version 2.14.1 (2011-12-22)
>
> I'm new to R (having previously used it only for graphics), but have worked in many other languages. I've got a CSV file from which I'd like to read the values from a single *row* into a vector. E.g., for a file such that
>
> $ head -n 2 ~/data/foo.csv | tail -n 1
> 5718,0.3,0.47,0,0,0,0,0,0,0,0,0.08,0.37,0,0,0.83,1.55,0,0,0,0,0,0,0,0,0,0.00,2.48,2.33,0.17,0,0,0,0,0,0,0.00,10.69,0.18,0,0,0,0
>
> I'd like to be able to populate a vector 'v' s.t. v[1]=5718, ... v[43]=0
>
> I can't seem to do that with, e.g., read.csv(...) or scan(...), both of which seem column-oriented. What am I missing?

Those are both column oriented, but you can change the result to a 
vector after reading it.

For example,

x <- read.csv("foo.csv", nrow=1)
x <- as.numeric(x[1,])  # convert to numeric vector

If you don't want the first row, use skip=<something> in the read.csv 
call.

Duncan Murdoch



More information about the R-help mailing list