[R] Error setting rowname if rowname currently NULL

jim holtman jholtman at gmail.com
Tue Mar 3 00:24:49 CET 2009


THe problem is that 'rownames(fred)' is NULL and therefore you will
have to define the names of all the rows:

> fred<-matrix(,4,2)
> fred
     [,1] [,2]
[1,]   NA   NA
[2,]   NA   NA
[3,]   NA   NA
[4,]   NA   NA
> rownames(fred)
NULL
> rownames(fred) <- c("Apple",'','','')
> fred
      [,1] [,2]
Apple   NA   NA
        NA   NA
        NA   NA
        NA   NA
>


On Mon, Mar 2, 2009 at 5:58 PM, snubian <stuart.allen at exemail.com.au> wrote:
>
> 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.
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



-- 
Jim Holtman
Cincinnati, OH
+1 513 646 9390

What is the problem that you are trying to solve?




More information about the R-help mailing list