[R] Why only a "" string for heading for row.names with write.csv with a matrix?

Earl F. Glynn efg at stowers-institute.org
Wed Aug 10 18:18:23 CEST 2005


Consider:
> x <- matrix(1:6, 2,3)
> rownames(x) <- c("ID1", "ID2")
> colnames(x) <- c("Attr1", "Attr2", "Attr3")

> x
    Attr1 Attr2 Attr3
ID1     1     3     5
ID2     2     4     6

> write.csv(x,file="x.csv")
"","Attr1","Attr2","Attr3"
"ID1",1,3,5
"ID2",2,4,6

Have I missed an easy way to get the "" string to be something meaningful?

There is no information in the "" string.  This column heading for the row
names often could used as a database key, but the "" entry would need to be
manually edited first.  Why not provide a way to specify the string instead
of putting "" as the heading for the rownames?

>From http://finzi.psych.upenn.edu/R/doc/manual/R-data.html

  Header line
  R prefers the header line to have no entry for the row names,
  . . .
  Some other systems require a (possibly empty) entry for the row names,
which is what write.table will provide if argument col.names = NA  is
specified. Excel is one such system.

Why is an "empty" entry the only option here?

A quick solution that comes to mind seems a bit kludgy:

> y <- cbind(rownames(x), x)
> colnames(y)[1] <- "ID"
> y
    ID    Attr1 Attr2 Attr3
ID1 "ID1" "1"   "3"   "5"
ID2 "ID2" "2"   "4"   "6"

> write.table(y, row.names=F, col.names=T, sep=",", file="y.csv")
"ID","Attr1","Attr2","Attr3"
"ID1","1","3","5"
"ID2","2","4","6"

Now the rownames have an "ID" header, which could be used as a key in a
database if desired without editing (but all the "numbers" are now
characters strings, too).

It's also not clear why I had to use write.table above, instead of
write.csv:
> write.csv(y, row.names=F, col.names=T, file="y.csv")
Error in write.table(..., col.names = NA, sep = ",", qmethod = "double") :
        col.names = NA makes no sense when row.names = FALSE

Thanks for any insight about this.

efg
--
Earl F. Glynn
Bioinformatics
Stowers Institute




More information about the R-help mailing list