我是Shiny的新手并且正在学习它的功能。使用mtcars数据,我试图创建一个图表,其轴将根据用户输入进行更改。当我运行应用程序时,我收到错误告诉我" x和y长度不一样",所以看起来"数据"在plot函数中指定的是没有接收mtcars dataframe列。如果我替换"数据"与服务器功能中列出的任何列。
shinyUI(navbarPage("My Application",
tabPanel("Component 1"),
tabPanel("Component 2"),
tabPanel("Component 3",
fluidPage(
fluidRow(
column(4,
"Sidebar",
helpText("This is my longer help text help text."),
selectInput("var",
label = "Choose a variable to display",
choices = c("mpg", "disp", "hp", "qsec"),
selected = "A")
),
column(8,
#style = "background-color:#4d3a7d;",
"Main",
textOutput("selected_var"),
plotOutput("plot1")
)
)
)
),
navbarMenu("More",
tabPanel("Sub-Component A"),
tabPanel("Sub-Component B"))
))
shinyServer(function(input, output) {
data <- reactive({
if("mpg" %in% input$var) return(mtcars$mpg)
if("disp" %in% input$var) return(mtcars$disp)
if("hp" %in% input$var) return(mtcars$hp)
if("qsec" %in% input$var) return(mtcars$qsec)
})
output$selected_var <- renderText({
paste("you have selected", input$var)
})
output$plot1 <- renderPlot({
plot(mtcars$wt, data)
})
})
答案 0 :(得分:0)
我想通了 - “数据”应该是“data()”。
答案 1 :(得分:0)
我们也可以使用switch
代替if
。此外,在selected
中的selectInput
中,它可能是choices
中的一个。不确定定义"A"
的位置
library(shiny)
-ui
ui <- navbarPage("My Application",
tabPanel("Component 1"),
tabPanel("Component 2"),
tabPanel("Component 3",
fluidPage(
fluidRow(
column(4,
"Sidebar",
helpText("This is my longer help text help text."),
selectInput("var",
label = "Choose a variable to display",
choices = c("mpg", "disp", "hp", "qsec"),
selected = "mpg")
),
column(8,
#style = "background-color:#4d3a7d;",
"Main",
textOutput("selected_var"),
plotOutput("plot1")
)
)
)
),
navbarMenu("More",
tabPanel("Sub-Component A"),
tabPanel("Sub-Component B"))
)
-server
server <- function(input, output) {
data <- reactive({
switch(input$var,
mpg = mtcars$mpg,
dist = mtcars$disp,
hp = mtcars$hp,
qsec = mtcars$qsec
)
})
output$selected_var <- renderText({
paste("you have selected", input$var)
})
output$plot1 <- renderPlot({
plot(mtcars$wt, data(), xlab = "wt", ylab = input$var)
})
}
shinyApp(ui = ui, server = server)
-output