代码之家  ›  专栏  ›  技术社区  ›  andrewj

将ftable转换为矩阵

  •  1
  • andrewj  · 技术社区  · 15 年前

    以下面的ftable为例

    height <- c(rep('short', 7), rep('tall', 3))
    girth <- c(rep('narrow', 4), rep('wide', 6))
    measurement <- rnorm(10)
    foo <- data.frame(height=height, girth=girth, measurement=measurement)
    ftable.result <- ftable(foo$height, foo$girth)
    

    我想把上面的转换成 ftable.result as.matrix() 不完全有效,因为它不会为您附加行名称和列名。

    ftable.matrix <- ftable.result
    class(ftable.matrix) <- 'matrix'
    
    rownames(ftable.matrix) <- unlist(attr(ftable.result, 'row.vars'))
    colnames(ftable.matrix) <- unlist(attr(ftable.result, 'col.vars'))
    

    然而,这似乎有点过于严厉。有没有更有效的方法?

    2 回复  |  直到 15 年前
        1
  •  2
  •   Shane    15 年前

    我发现 2 solutions on R-Help :

    head(as.table(ftable.result), Inf)
    

    t <- as.table(ftable.result)
    class(t) <- "matrix"
    
        2
  •  2
  •   A5C1D2H2I1M1N2O1R2T1    11 年前

    原来@Shane最初发布了(但很快删除了)什么 用R的最新版本给出了正确答案。

    在路上的某个地方,一个 as.matrix 方法被添加为 ftable (不过,我在通读的新闻文件中没有找到它。

    A.矩阵 方法 让您可以相当好地处理“嵌套”频率表(这是 可折叠 创建非常好)。考虑以下事项:

    temp <- read.ftable(textConnection("breathless yes no
    coughed yes no
    age
    20-24  9  7  95 1841
    25-29 23  9 108 1654
    30-34 54 19 177 1863"))
    
    class(temp)
    # [1] "ftable"
    

    这个 head(as.table(...), Inf) 这种把戏对这样的人不起作用 ftables 因为 as.table

    head(as.table(temp), Inf)
    #  [1]    9   23   54   95  108  177    7    9   19 1841 1654 1863
    

    出于同样的原因,第二个建议也不起作用:

    t <- as.table(temp)
    class(t) <- "matrix"
    # Error in class(t) <- "matrix" : 
    #   invalid to set the class to matrix unless the dimension attribute is of length 2 (was 3)
    

    然而,对于R的最新版本,只需使用 可以:

    as.matrix(temp)
    #        breathless_coughed
    # age     yes_yes yes_no no_yes no_no
    #   20-24       9      7     95  1841
    #   25-29      23      9    108  1654
    #   30-34      54     19    177  1863
    
    class(.Last.value)
    # [1] "matrix"
    

    如果你喜欢 data.frame matrix table2df 从我的 "mrdwabmisc" package on GitHub