R:表和多维数组中的维名称

mzu*_*uba 10 r type-conversion multidimensional-array dataframe

由于我使用的函数需要一个表对象作为参数,我想将一个多维数组转换为一个表,但我有维度名称的问题.

如帮助文件中所指定as.table,dnn参数应包含dimnames名称.

dnn … the names to be given to the dimensions in the result (the dimnames names).
Run Code Online (Sandbox Code Playgroud)

但即使在指定时dnn,我生成的表as.table也没有维度名称.

以下代码说明了我的问题.

>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
Run Code Online (Sandbox Code Playgroud)

现在从数组构造表时尝试相同:

>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
Run Code Online (Sandbox Code Playgroud)

Rol*_*and 17

as.table没有dnn争论.您需要手动设置dimnames.

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
Run Code Online (Sandbox Code Playgroud)