我想在我的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)}
答案 0 :(得分: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
对象:
rownames=True
然后我们要做的就是在renderTable
中设置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)
。希望这有帮助!
工作示例:
depth= 1