[R] Help with read.csv2

Marc Schwartz (via MN) mschwartz at mn.rr.com
Thu Nov 17 19:06:07 CET 2005


On Thu, 2005-11-17 at 17:09 +0100, Matthieu Cornec wrote:
> Hello,
>  I am importing the following file
>   ;aa;bb;cc
> 1988;12;12;12
> 1989;78;78;12
> 1990;78;78;12
> 1991;78;78;12
> 1992;78;78;12
> 1993;78;78;12
> 1994;78;78;12
> ------------------------------------------------
> data<-read.csv2("test.csv",header=T)
> ------------------------------------------
> it gives
>   X aa bb cc
> 1 1988 12 12 12
> 2 1989 78 78 12
> 3 1990 78 78 12
> 4 1991 78 78 12
> 5 1992 78 78 12
> 6 1993 78 78 12
> 7 1994 78 78 12
>  How do I get :
> ------------------------
>  aa bb cc
> 1988 12 12 12
> 1989 78 78 12
> 1990 78 78 12
> 1991 78 78 12
> 1992 78 78 12
> 1993 78 78 12
> 1994 78 78 12
> ----------------------------

Are you indicating that you want the years to be the rownames and NOT a
column in the data frame?

If so, use the 'row.names' argument to indicate that the first column of
the incoming data file contains the rownames:

> dat <- read.csv2("clipboard", row.names = 1)

> dat
     aa bb cc
1988 12 12 12
1989 78 78 12
1990 78 78 12
1991 78 78 12
1992 78 78 12
1993 78 78 12
1994 78 78 12

> str(dat)
`data.frame':   7 obs. of  3 variables:
 $ aa: int  12 78 78 78 78 78 78
 $ bb: int  12 78 78 78 78 78 78
 $ cc: int  12 12 12 12 12 12 12

> rownames(dat)
[1] "1988" "1989" "1990" "1991" "1992" "1993" "1994"



Note that you are getting the "X" in your initial example above, since
you are missing the first column name in the text file. A better
approach here might be (depending upon your intent) to use the
'col.names' argument to specify the column names explicitly:

> dat <- read.csv2("clipboard", header = TRUE, 
                    col.names = c("Years", "aa", "bb", "cc"))

> dat
  Years aa bb cc
1  1988 12 12 12
2  1989 78 78 12
3  1990 78 78 12
4  1991 78 78 12
5  1992 78 78 12
6  1993 78 78 12
7  1994 78 78 12

This way, you are defining the first column name during the import and
your 'Years' are available as a data column. It all depends upon what
you want to do with the data at this point.

HTH,

Marc Schwartz




More information about the R-help mailing list