Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: Dimension names in tables and multi-dimensional arrays

Since a function that I use requires a table object as parameter, I would like to convert a multidimensional array to a table, but I have problems with dimension names.

As specified in the help file of as.table, the dnn parameter should contain dimnames names.

dnn … the names to be given to the dimensions in the result (the dimnames names).

But even when specifying dnn, my tables produced by as.table have no dimension names.

The following code illustrates my problem.

>test <- table(c("a","b","c","c","c"),c("1","2","3","2","2"),dnn=c("letters","numbers"))
>test 

          numbers
letters 1 2 3
      a 1 0 0
      b 0 1 0
      c 0 2 1

# this works perfectly

now try the same when constructing the table from an array:

>my2dimdata <- array(c(1,0,0,0,1,2,0,0,1),dim=c(3,3),
                    dimnames=list(c("a","b","c"),
                                  c("1","2","3")))
>my2dimdata

  1 2 3
a 1 0 0
b 0 1 0
c 0 2 1

# the array as expected

>my2dimtable <- as.table(my2dimdata,dnn=c("letters","numbers"))
>my2dimtable

  1 2 3
a 1 0 0
b 0 1 0
c 0 2 1

# there are no dimnames
like image 309
mzuba Avatar asked Feb 13 '14 12:02

mzuba


1 Answers

as.table doesn't have a dnn argument. You need to set the dimnames manually.

my2dimdata <- array(c(1,0,0,0,1,2,0,0,1),dim=c(3,3),
                    dimnames=list(c("a","b","c"),
                                  c("1","2","3")))

my2dimdata <- as.table(my2dimdata)
names(attributes(my2dimdata)$dimnames) <- c("letters","numbers")

#        numbers
# letters 1 2 3
#       a 1 0 0
#       b 0 1 0
#       c 0 2 1
like image 183
Roland Avatar answered Nov 09 '22 22:11

Roland