Pivot Table-like Output in R?

后端 未结 4 404
慢半拍i
慢半拍i 2021-01-31 22:16

I am writing a report that requires the generation of a number of pivot tables in Excel. I would like to think there is a way to do this in R so that I can avoid Excel. I would

4条回答
  •  温柔的废话
    2021-01-31 22:57

    Sorry for autopromotion but take a look at my package expss.

    Code for generating output below:

    set.seed(1)
    school  <- sample(c("BSA1", "BSA2", "HSA1"), 100, replace=T)
    teacher <- sample(c("Tom", "Dick", "Harry"), 100, replace=T)
    growth <- rnorm(100, 5, 3)
    
    myDf <- data.frame(school, teacher, growth)
    
    library(expss)
    myDf %>% 
        # 'tab_cells' - variables on which statistics will be calculated
        # "|" is needed to suppress 'growth' in row labels
        tab_cells("|" = growth) %>%  
        # 'tab_cols' - variables for columns. Can be ommited
        tab_cols(total(label = "")) %>% 
        # 'tab_rows' - variables for rows.
        tab_rows(school %nest% list(teacher, "(All)"), "|" = "(All)") %>% 
        # 'method = list' is needed for statistics labels in column
        tab_stat_fun("Average Growth" = mean, 
                     "Std Dev" = sd, 
                     "# of scholars" = length, 
                     method = list) %>% 
        # finalize table
        tab_pivot()
    

    Code above gives object inherited from data.frame which can be used with standard R operations (subsetting with [ and etc.). But there is a special print method for this object. Console output:

     |       |       | Average Growth | Std Dev | # of scholars |
     | ----- | ----- | -------------- | ------- | ------------- |
     |  BSA1 |  Dick |            4.7 |     3.7 |            14 |
     |       | Harry |            4.3 |     1.4 |             9 |
     |       |   Tom |            5.5 |     4.0 |             4 |
     |       | (All) |            4.7 |     3.1 |            27 |
     |  BSA2 |  Dick |            6.1 |     2.3 |            15 |
     |       | Harry |            5.0 |     2.9 |             9 |
     |       |   Tom |            4.3 |     2.8 |            14 |
     |       | (All) |            5.2 |     2.7 |            38 |
     |  HSA1 |  Dick |            4.5 |     2.9 |            11 |
     |       | Harry |            4.9 |     3.0 |            13 |
     |       |   Tom |            4.7 |     3.2 |            11 |
     |       | (All) |            4.7 |     3.0 |            35 |
     | (All) |       |            4.9 |     2.9 |           100 |
    

    Output via htmlTable in knitr, RStudio viewer or Shiny:

提交回复
热议问题