gpt4 book ai didi

R Shiny 数据不可用 "Error: object not found"

转载 作者:行者123 更新时间:2023-12-05 06:32:45 28 4
gpt4 key购买 nike

在 Shiny 应用程序中绘制条形图时,生成的数据帧仅可用于第一个而不是第二个图(“错误:未找到对象 df2”)。将用于生成数据帧的代码复制并粘贴到第二个 renderPlot 部分可以解决问题,但这是多余的并且会降低应用程序的速度。是否有更优雅的方式让数据在多个 renderPlot 部分可用?我尝试使用 Shinys reactive() 函数但没有成功。

这是一个最小的例子:

library(shiny)
library(ggplot2)

# Define UI for application that draws a histogram
ui <- fluidPage(

titlePanel("Utility"),

sidebarLayout(
sidebarPanel(
sliderInput("var1",
"N",
min = 1,
max = 100,
value = 20)),
mainPanel(
plotOutput("barplot1"),
plotOutput("barplot2"))))



# Define server logic required to draw a barplot
server <- function(input, output) {

output$barplot1 <- renderPlot({

df <- as.data.frame(matrix(c(
"A", "1", rnorm(1, input$var1, 1),
"A", "2", rnorm(1, input$var1, 1),
"B", "1", rnorm(1, input$var1, 1),
"B", "2", rnorm(1, input$var1, 1)),
nrow = 4, ncol=3, byrow = TRUE))
df$V3 <- as.numeric(as.character(df$V3))

df2 <- as.data.frame(matrix(c(
"A", "1", rnorm(1, input$var1, df[1,3]),
"A", "2", rnorm(1, input$var1, df[1,3]),
"B", "1", rnorm(1, input$var1, df[1,3]),
"B", "2", rnorm(1, input$var1, df[1,3])),
nrow = 4, ncol=3, byrow = TRUE))
df2$V3 <- as.numeric(as.character(df$V3))

ggplot(df, aes(x=V1, y=V3, fill=V2)) +
geom_bar(stat="identity")

})

output$barplot2 <- renderPlot({

ggplot(df2, aes(x=V1, y=V3, fill=V2)) +
geom_bar(stat="identity")

})
}

# Run the application
shinyApp(ui = ui, server = server)

最佳答案

是的,您永远不应该复制您的数据。要使您的数据框可用于所有函数,只需使用 reactive 动态生成它(因为它取决于 input$var1)。当调用响应式变量x时,您需要使用x()而不是x。否则,您会收到以下错误:Error: object of type 'closure' is not subsettable"。因此,在您的情况下,使 df react 需要您使用df() 代替。

server <- function(input, output) {

df <- reactive(
data.frame(V1 = c("A", "A", "B", "B"),
V2 = c("1", "2", "1", "2"),
V3 = rnorm(1, input$var1, 5)
)
)

output$barplot1 <- renderPlot({
ggplot(df(), aes(x=V1, y=V3, fill=V2)) +
geom_bar(stat="identity")
})

output$barplot2 <- renderPlot({
ggplot(df(), aes(x=V1, y=V3, fill=V2)) +
geom_bar(stat="identity")
})
}

关于R Shiny 数据不可用 "Error: object not found",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51099987/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com