使用 input$ 调用数据集
Using input$ to call the dataset
假设我的数据集中有 2 列,我想根据我们所在的列输出直方图和摘要,目前我每个输出有 2 个 if 语句检查输入等于什么。
ui <- fluidPage(
titlePanel("First iteration"),
sidebarLayout(
sidebarPanel("Sidebar Panel",
selectInput("typetoshow", "Choose what you want to display",
choices = c("pts", "upts"))
),
mainPanel("main panel",
plotOutput("hist"),
verbatimTextOutput("sum")
)
)
)
server <- function(input, output){
output$hist <- renderPlot({
if (input$typetoshow == "pts"){
hist(data$pts)
}
if (input$typetoshow == "upts"){
hist(data$upts)
}
})
output$sum <- renderPrint({
if (input$typetoshow == "pts"){
summary(data$pts)
}
if (input$typetoshow == "upts"){
summary(data$upts)
}
})
}
我试过
hist(data$input$typetoshow)
但它给我一个错误,在直方图中显示 'x must be numeric' 并在输出摘要中显示 NULL,有没有什么方法可以做到这一点而不用做很多 if 语句?我将一次处理 10 多列,所以我希望代码整洁。
我们可以在顶部使用 req
,然后使用 [[
根据 'input$typetoshow'
中的值对数据集列进行子集化
server <- function(input, output){
output$hist <- renderPlot({
req(input$typetoshow)
hist(data[[input$typetoshow]])
})
output$sum <- renderPrint({
req(input$typetoshow)
summary(data[[input$typetoshow]])
})
您可以使用 dplyr::select
使其更简单:
server <- function(input, output){
output$hist <- renderPlot({
hist(unlist(dplyr::select(data, input$typetoshow)))
})
output$sum <- renderPrint({
summary(dplyr::select(data, input$typetoshow))
})
}
假设我的数据集中有 2 列,我想根据我们所在的列输出直方图和摘要,目前我每个输出有 2 个 if 语句检查输入等于什么。
ui <- fluidPage(
titlePanel("First iteration"),
sidebarLayout(
sidebarPanel("Sidebar Panel",
selectInput("typetoshow", "Choose what you want to display",
choices = c("pts", "upts"))
),
mainPanel("main panel",
plotOutput("hist"),
verbatimTextOutput("sum")
)
)
)
server <- function(input, output){
output$hist <- renderPlot({
if (input$typetoshow == "pts"){
hist(data$pts)
}
if (input$typetoshow == "upts"){
hist(data$upts)
}
})
output$sum <- renderPrint({
if (input$typetoshow == "pts"){
summary(data$pts)
}
if (input$typetoshow == "upts"){
summary(data$upts)
}
})
}
我试过
hist(data$input$typetoshow)
但它给我一个错误,在直方图中显示 'x must be numeric' 并在输出摘要中显示 NULL,有没有什么方法可以做到这一点而不用做很多 if 语句?我将一次处理 10 多列,所以我希望代码整洁。
我们可以在顶部使用 req
,然后使用 [[
根据 'input$typetoshow'
server <- function(input, output){
output$hist <- renderPlot({
req(input$typetoshow)
hist(data[[input$typetoshow]])
})
output$sum <- renderPrint({
req(input$typetoshow)
summary(data[[input$typetoshow]])
})
您可以使用 dplyr::select
使其更简单:
server <- function(input, output){
output$hist <- renderPlot({
hist(unlist(dplyr::select(data, input$typetoshow)))
})
output$sum <- renderPrint({
summary(dplyr::select(data, input$typetoshow))
})
}