Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change name of row variable in a table

Tags:

r

It's easy to change the names of the rows (e.g., with rownames()), but that's not what I'm after. Consider:

> newTab <- xtabs(~as.factor(letters[1:2])+LETTERS[1:2])
> newTab
                       LETTERS[1:2]
as.factor(letters[1:2]) A B
                      a 1 0
                      b 0 1

I want to get this:

          upper case
lower case A B
         a 1 0
         b 0 1

But if I try:

> dimnames(newTab) <- list("lower case", "upper case")

I get an error:

Error in dimnames(newTab) <- list("lower case", "upper case") :
length of 'dimnames' [1] not equal to array extent

like image 828
gung - Reinstate Monica Avatar asked Aug 09 '13 20:08

gung - Reinstate Monica


1 Answers

Look at the output of str(newTab):

> str(newTab)
 xtabs [1:2, 1:2] 1 0 0 1
 - attr(*, "dimnames")=List of 2
  ..$ as.factor(letters[1:2]): chr [1:2] "a" "b"
  ..$ LETTERS[1:2]           : chr [1:2] "A" "B"
 - attr(*, "class")= chr [1:2] "xtabs" "table"
 - attr(*, "call")= language xtabs(formula = ~as.factor(letters[1:2]) + LETTERS[1:2])

as.factor(letters[1:2]) and LETTERS[1:2] are the names of the dimnames list. So you really want to set the names of the dimnames list, not the dimnames themselves. You can do that via something like:

> dimnames(newTab) <- setNames(dimnames(newTab),c("lower case", "upper case"))
> # or
> names(dimnames(newTab)) <- c("lower case", "upper case")
> newTab
          upper case
lower case A B
         a 1 0
         b 0 1
like image 108
Joshua Ulrich Avatar answered Sep 30 '22 18:09

Joshua Ulrich