【问题标题】:Display Crosstab Correctly in Shiny在 Shiny 中正确显示交叉表
【发布时间】:2018-01-27 21:12:08
【问题描述】:

我想在我的 Shiny 应用程序中显示一个简单的交叉表,但 renderTable 函数似乎重新格式化了表格。 renderTable中的表格如何构造,或者有其他方法可以显示我原来的表格吗?

purchase_by_sex = table(sales$purch_freq, sales$sex)

这可以让我在控制台中获得所需的输出;

                     Female Male
  Once a Week           3    9
  Once a Month          7   11
  Every 2-3 Months      6    8
  < Every 3 Months      5    2
  Never                20   15
  Don't Know            6    8

但会在 Shiny 中重新格式化;

Var1                Var2     Freq
Once a Week         Female    3
Once a Month        Female    7
Every 2-3 Months    Female    6
< Every 3 Months    Female    5
Never               Female    20

ui <- fluidPage( tableOutput("table2") )

server <- function(input, output) {
    output$table2 <- renderTable(purchase_by_sex, striped=TRUE, bordered = TRUE)}

【问题讨论】:

    标签: r shiny


    【解决方案1】:

    renderTable() 期望 data.frame 作为输入,table(sales$purch_freq, sales$sex) 的结果不是。试试:

    class(table(sales$purch_freq, sales$sex))
    

    返回:

    [1] "table".
    

    我认为 renderTable 因此将表格解析为 data.frame 本身,实际上我们可以看到 as.data.frame(purchase_by_sex) 创建了您不希望的输出:

           Var1   Var2 Freq
    1     often female    2
    2    rarely female    5
    3 sometimes female    1
    4     often   male    6
    5    rarely   male    4
    6 sometimes   male    2
    

    您可以使用as.data.frame.matrix(purchase_by_sex) 函数将表格转换为具有正确布局的data.frame 对象:

              female male
    often          2    6
    rarely         5    4
    sometimes      1    2
    

    然后我们要做的就是在renderTable 中设置rownames=True。希望这会有所帮助!


    工作示例:

    library(shiny)
    
    sales = data.frame(sex=sample(c('male','female'),20,TRUE),purch_freq=sample(c('sometimes','often','rarely'),20,TRUE))
    
    purchase_by_sex = table(sales$purch_freq, sales$sex)
    
    ui <- fluidPage(
      tableOutput("table2"),
      tableOutput("table3")
    
    )
    
    # create the server
    server <- function( input, output, session ){
      output$table2 <- renderTable( purchase_by_sex, striped=TRUE, bordered = TRUE)
      output$table3 <- renderTable( as.data.frame.matrix(purchase_by_sex), striped=TRUE, bordered = TRUE,rownames = T)
    
      }
    
    
    shiny::shinyApp( ui = ui, server = server)
    

    【讨论】:

      猜你喜欢
      • 2014-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多