【发布时间】:2017-08-16 19:33:14
【问题描述】:
目标
我有两个数据表:DT1 和 DT2。每个都有一个 X 变量:x,和三个 Y 变量:y1、y2 和 y3。我的目标是创建一个基本的 Shiny 应用程序,其中数据集和 Y 变量都可由用户选择。
小例子
数据
library(data.table)
set.seed(123)
#y1 between 1 and 50
DT1 <- data.table(x=c(1:10),
y1 = round(runif(10, 1, 50)))
#y2 between 51 and 100
DT2 <- data.table(x=c(1:10),
y1 = round(runif(10, 51, 100)))
#y2 and y3 are double and triple multiples of y1
DT1[, y2 := y1*2][, y3 := y1*3]
DT2[, y2 := y1*2][, y3 := y1*3]
版本一:只有数据输入
library(shiny)
library(ggplot2)
ui <- fluidPage(
selectInput(inputId = 'input1', label = 'Choose a data table',
choices = c("1st" = "data1", "2nd" = "data2")),
plotOutput(outputId = "graph")
)
server <- function(input, output) {
output$graph <- renderPlot({
dt <- switch(input$input1, data1=DT1, data2=DT2) #data switch
ggplot(dt, aes(x, y1)) + geom_point() + geom_line()
})
}
shinyApp(ui, server)
到目前为止,一切都很好。该应用程序正常工作,并且用户可以选择正在绘制的数据表。
版本 2:添加 Y 变量输入
library(shiny)
library(ggplot2)
ui <- fluidPage(
selectInput(inputId = 'input1', label = 'Choose a data table',
choices = c("1st" = "data1", "2nd" = "data2")),
selectInput(inputId = 'input2', label = 'Choose a Y-variable',
choices = c("Y-1" = "Y_1", "Y-2" = "Y_2", "Y-3" = "Y_3")),
plotOutput(outputId = "graph")
)
server <- function(input, output) {
output$graph <- renderPlot({
dt <- switch(input$input1, data1=DT1, data2=DT2) #data switch
var <- switch(input$input2, Y_1=y1, Y_2=y2, Y_3=y3) #Y-variable switch
ggplot(dt, aes(x, var)) + geom_point() + geom_line()
})
}
shinyApp(ui, server)
这行不通!
有什么问题?
【问题讨论】: