[英]R: Shiny Using variables under data Reactive
我正在嘗試使用在數據react()下創建的變量。 以下是我的代碼。 這是一個隨時可以使用的示例
library(shiny)
shinyUI(fluidPage(
titlePanel("Old Data"),
# Sidebar with a slider input for number of bins
sidebarLayout(
sidebarPanel(
selectInput("var",
label = "Choose a Group to Display",
choices = c("4", "6","8"),
selected = "4")
),
# Show a plot of the generated distribution
mainPanel(
plotOutput("Plot1"),
plotOutput("Plot2")
)
)
))
library(shiny)
library(datasets)
library(ggplot2)
cars=mtcars
shinyServer(function(input, output) {
data_rec =reactive({
d=cars[cars$cyl==input$var,]
d1=d[d$am==0,]
list(d=d,d1=d1)
})
output$Plot1 <- renderPlot({
data2=data_rec()
ggplot(data2$d,aes(x=gear,y=wt))+geom_boxplot() })
output$Plot2 <- renderPlot({
ggplot(data2$d1,aes(x=gear,y=wt))+geom_boxplot() })
})
我只能為另一個創建1個圖表,但收到錯誤:找不到對象“ data2”。 幫助我在數據反應式內部定義變量,然后使用它們進行繪圖。
我認為這里對變量的范圍有一些困惑。 data2
沒有在output$plot2
代碼塊中定義,並且它與output$plot1
代碼塊中定義的定義沒有共享。
我想這你想要做什么,但我會用一個reactiveValues
的data_rec
。
library(shiny)
library(datasets)
library(ggplot2)
u <- shinyUI(fluidPage(
titlePanel("Old Data"),
# Sidebar with a slider input for number of bins
sidebarLayout(
sidebarPanel(
selectInput("var",
label = "Choose a Group to Display",
choices = c("4", "6","8"),
selected = "4")
),
# Show a plot of the generated distribution
mainPanel(
plotOutput("Plot1"),
plotOutput("Plot2")
)
)
))
cars=mtcars
s <- shinyServer(function(input, output) {
data_rec =reactive({
req(input$var)
d=cars[cars$cyl==input$var,]
d1=d[d$am==0,]
list(d=d,d1=d1)
})
output$Plot1 <- renderPlot({
data2=data_rec()
ggplot(data2$d,aes(x=gear,y=wt))+geom_boxplot()
})
output$Plot2 <- renderPlot({
data2=data_rec()
ggplot(data2$d1,aes(x=gear,y=wt))+geom_boxplot()
})
})
shinyApp(u,s)
產生:
您忘記在output$Plot2
創建數據。
它看起來應該像這樣:
output$Plot2 <- renderPlot({
data2 <- data1()
data2$d1 %>%
ggplot +
aes(x = gear,y = wt) +
geom_boxplot()
})
您還可以將反應部件直接放入renderPlot函數中,並避免讓列表與ggplot一起使用...
服務器部分如下所示:
server <- shinyServer(function(input, output) {
output$Plot1 <- renderPlot({
data %>%
filter(cyl == input$var) %>%
ggplot +
aes(x = gear, y = wt) +
geom_boxplot()
})
output$Plot2 <- renderPlot({
data %>%
filter(cyl == input$var & am == 0) %>%
ggplot +
aes(x = gear,y = wt) +
geom_boxplot()
})
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.