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

From: Earl F. Glynn <efg_at_stowers-institute.org>
Date: Thu 11 Aug 2005 - 02:18:23 EST


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

______________________________________________
R-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
Received on Thu Aug 11 02:28:20 2005

This archive was generated by hypermail 2.1.8 : Fri 03 Mar 2006 - 03:39:45 EST