[R] Error setting rowname if rowname currently NULL

snubian stuart.allen at exemail.com.au
Mon Mar 2 23:58:58 CET 2009


Hi,

My first post here and new to R so please bear with me (long time programmer
though, helping a friend with some scripts).

I've noticed a behaviour when using rownames() that I think is odd,
wondering if I'm doing something wrong.

To illustrate, say I create a very simple matrix (called fred):

fred<-matrix(,4,2)

It looks like this:

     [,1] [,2]
[1,]   NA   NA
[2,]   NA   NA
[3,]   NA   NA
[4,]   NA   NA

If I now try and set a row name for one of the rows (say the first row) to
"APPLE", by doing this:

rownames(fred)[1] <- "APPLE"

I get an error:

Error in dimnames(x) <- dn : 
  length of 'dimnames' [1] not equal to array extent

However, I found that if I first set all the rownames to anything at all, by
using say:

rownames(fred) <- c(1:4)

Which gives me:

  [,1] [,2]
1   NA   NA
2   NA   NA
3   NA   NA
4   NA   NA

Then my desired command works, and thus:

rownames(fred)[1] <- "APPLE"

Gives me what I want:

      [,1] [,2]
APPLE   NA   NA
2       NA   NA
3       NA   NA
4       NA   NA

So, what this says to me is that to set the row names INDIVIDUALLY, they
first need to be set to something (anything!).

For what I am doing, I need to set the row names one at a time, as I iterate
through a loop. So I found that to do this I first had to set the rownames
to some dummy values as above. Then it works fine. But this seems a little
kludgy and unnecessary to me, and I am wondering what I am doing wrong. Have
just started in R so fumbling my way through somewhat.

Any suggestions would be appreciated, thanks!


-- 
View this message in context: http://www.nabble.com/Error-setting-rowname-if-rowname-currently-NULL-tp22298797p22298797.html
Sent from the R help mailing list archive at Nabble.com.




More information about the R-help mailing list