Using attributes of `ftable` for extracting data

前端 未结 2 727
梦毁少年i
梦毁少年i 2021-02-12 17:33

I sometimes use the ftable function purely for its presentation of hierarchical categories. However, sometimes, when the table is large, I would like to further sub

2条回答
  •  渐次进展
    2021-02-12 18:07

    Here's what I was able to sort of hack together, with some help from Axeman:

    replace_empty_arguments <- function(a) {
      empty_symbols <- vapply(a, function(x) {
        is.symbol(x) && identical("", as.character(x)), 0)
      } 
      a[!!empty_symbols] <- 0
      lapply(a, eval)
    }
    
    `[.ftable` <- function (inftable, ...) {
      if (!class(inftable) %in% "ftable") stop("input is not an ftable")
      tblatr <- attributes(inftable)[c("row.vars", "col.vars")]
      valslist <- replace_empty_arguments(as.list(match.call()[-(1:2)]))
      x <- sapply(valslist, function(x) identical(x, 0))
      TAB <- as.table(inftable)
      valslist[x] <- dimnames(TAB)[x]
      temp <- as.matrix(expand.grid(valslist))
      out <- ftable(
        `dimnames<-`(`dim<-`(TAB[temp], lengths(valslist)), valslist),
        row.vars = seq_along(tblatr[["row.vars"]]),
        col.vars = seq_along(tblatr[["col.vars"]]) + length(tblatr[["row.vars"]]))
      names(attributes(out)[["row.vars"]]) <- names(tblatr[["row.vars"]])
      names(attributes(out)[["col.vars"]]) <- names(tblatr[["col.vars"]])
      out
    }
    

    Try it out with the examples from the question:

    mytable[c("1st", "3rd"), , "Child", ]
    ##                    Survived No Yes
    ## Class Sex    Age                  
    ## 1st   Male   Child           0   5
    ##       Female Child           0   1
    ## 3rd   Male   Child          35  13
    ##       Female Child          17  14
    
    mytable[c("1st", "3rd"), , , "No"]
    ##                    Survived  No
    ## Class Sex    Age               
    ## 1st   Male   Child            0
    ##              Adult          118
    ##       Female Child            0
    ##              Adult            4
    ## 3rd   Male   Child           35
    ##              Adult          387
    ##       Female Child           17
    ##              Adult           89
    
    tab2[c("1st", "3rd"), , , ]
    ##              Age      Child     Adult    
    ##              Survived    No Yes    No Yes
    ## Class Sex                                
    ## 1st   Male                0   5   118  57
    ##       Female              0   1     4 140
    ## 3rd   Male               35  13   387  75
    ##       Female             17  14    89  76
    

提交回复
热议问题