【问题标题】:R: Dimension names in tables and multi-dimensional arraysR:表和多维数组中的维度名称
【发布时间】:2014-03-12 07:49:43
【问题描述】:

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

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

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

但即使指定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

现在在从数组构造表时尝试同样的方法:

>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

【问题讨论】:

    标签: r multidimensional-array dataframe type-conversion


    【解决方案1】:

    as.table 没有 dnn 参数。您需要手动设置暗名。

    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
    

    【讨论】:

    • 谢谢!另请注意,names(attributes(my2dimdata)$dimnames) 正确地指代那些有问题的 dimnames 名称,而 dimnames(my2dimdata) 则完全不同。
    猜你喜欢
    • 1970-01-01
    • 2015-08-29
    • 1970-01-01
    • 2021-03-05
    • 1970-01-01
    • 2013-12-08
    • 2016-07-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多