[R] Error setting rowname if rowname currently NULL

Wacek Kusnierczyk Waclaw.Marcin.Kusnierczyk at idi.ntnu.no
Tue Mar 3 09:06:54 CET 2009


snubian wrote:

<snip>

> 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
>   

... and

    rownames(fred)
    # NULL


> 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"
>   

... so now rownames(fred) would have to become a vector of length one,
and you're trying to use a vector of length one to name rows in a matrix
with four rows.  (in principle, you could argue that the vector should
be recycled on such an occassion, as it happens in many other situations.)

hence

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

... because 1 != 4


> However, I found that if I first set all the rownames to anything at all, by
> using say:
>
> rownames(fred) <- c(1:4)
>   

... so that length(rownames(fred)) == 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"
>   

... whereby you change one element in rownames(fred) and it still has 4
elements


> 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!).
>   

not exactly true:

    fred = matrix(, 4, 2)
    rownames(fred)[4] = 'foo'

here you'd set the 4th element of rownames(fred), which fill the first
three with NA, and rownames(fred) has length 4, as needed.


> For what I am doing, I need to set the row names one at a time, as I iterate
> through a loop. 

is it possible that you don't really need it?

vQ




More information about the R-help mailing list