r - R Shiny 中是否有 R 函数来了解跨类别的均值
问题描述
我需要使下面的代码交互。我需要知道表中类别的含义。执行代码后,出现以下错误:
$ 运算符对原子向量无效
我在代码中看到一些错误
output$mean <- renderUI({tapply(Unit_Price, Material, mean)})
Unit_Price <- c(60, 49, 40, 61, 64, 60, 59, 54, 62, 69, 70, 42, 56,
61, 61, 61, 58, 51, 48, 65, 49, 49, 41, 48, 52, 46,
59, 46, 58, 43)
Material <- c("tas", "sa", "qld", "nsw", "nsw", "nt", "wa", "wa",
"qld", "vic", "nsw", "vic", "qld", "qld", "sa", "tas",
"sa", "nt", "wa", "vic", "qld", "nsw", "nsw", "wa",
"sa", "act", "nsw", "vic", "vic", "act")
library(shiny)
ui <- fluidPage(
sidebarLayout(
sidebarPanel(selectInput("x","Value of x",choices = c("ComA","ComB")),
checkboxInput("mean","Mean Prices are"),
uiOutput("mean")),
mainPanel(h6("Here it is"),
tableOutput("message")
)
)
)
server <- function(input, output, session) {
output$message <- renderTable(
{
if(input$x == "ComA")
{
data.frame(Unit_Price,Material)
} else
{
if(input$x == "ComB")
{
data.frame(Material=c("A","B"),Unit_Price=c(7,8))
}
}
}
)
output$mean <- renderUI({tapply(Unit_Price, Material, mean)})
}
shinyApp(ui, server)
解决方案
如果您交换 the renderUI
,renderTable
至少您不会再收到错误消息。
那是服务器部分:
output$mean <- renderTable(rownames = TRUE, {
a <- tapply(Unit_Price, Material, mean)
data.frame(a)
})
UI 部分也必须相应地进行调整。就这样uiOutput
变成了tableOutput
。
但对我来说,你实际上想要达到的目标仍然不是很清楚。数据是否应该是交互的Unit_Price
,Material
以便你计算当前选择的data.frame的手段?如果是这样,那么在 a 中创建该 data.frame 是有意义的reactive
,您可以在所有其他服务器功能中访问它。
现在,您只需在它们之间切换并在表格中显示它们,但始终为您在服务器功能之外分配的值计算平均值。
这是一个对数据使用响应式的示例。
编辑:由于 mean 表只应在单击复选框时出现,因此我包含了一个小req(input$mean)
的 in output$mean
,它等到单击复选框并返回 TRUE,否则代码将不会运行,并且表不会显示。
library(shiny)
ui <- fluidPage(
sidebarLayout(
sidebarPanel(selectInput("x","Value of x",choices = c("ComA","ComB")),
checkboxInput("mean","Mean Prices are"),
tableOutput("mean")),
mainPanel(h6("Here it is"),
tableOutput("message")
)
)
)
server <- function(input, output, session) {
data <- reactive({
if (input$x == "ComA") {
data.frame(Unit_Price, Material)
} else if (input$x == "ComB") {
data.frame(Material=c("A","B"), Unit_Price=c(7,8))
}
})
output$message <- renderTable({
data()
})
output$mean <- renderTable(rownames = TRUE, {
req(input$mean)
df <- data()
tapply(df$Unit_Price, df$Material, mean)
})
}
shinyApp(ui, server)
推荐阅读
- python - SyntaxError:f 字符串表达式部分不能包含反斜杠
- blazor - Blazor 组件生命周期 - 在设置参数后但在绑定之前如何在组件中执行异步操作
- python - Selenium 无效参数异常 - python
- regex - 匹配方法参数,包括字符串
- javascript - 遍历 getElementsByClassName 节点列表的子元素。无法使其正常工作
- flutter - 当我从 Flutter 中的某个页面返回时调用哪个方法?
- javascript - JavaScript:事件侦听器函数无法识别屏幕上某个点过去的事件
- python - 如何为分类数据添加标签?
- reporting-services - SSRS 目标线按类别在条形图上
- dask - dask 中自定义图形的注释