【问题标题】:r shiny storing plot and data frame in listr闪亮的存储图和数据框在列表中
【发布时间】:2022-01-22 20:29:44
【问题描述】:

我试图通过将函数的输出存储在列表中然后调用列表值来输出图表和数据框,但我的图表没有显示并且没有错误消息。我创建了一个虚拟示例来展示我的问题。

这是我的代码

library(shiny)

ui <- fluidPage(
    
    titlePanel("title"),
    
    sidebarLayout(
        sidebarPanel(
            checkboxInput("EF", "Efficient Frontier"),
            actionButton("Go", "Go", style="color: #fff; background-color: #337ab7; border-color: #2e6da4; margin: auto")
        ),
        
        mainPanel(
            fluidRow(
                align = "center",
                plotOutput("GraphEF")),
                tableOutput("EFWeightsTable")
        )
    )
)

server <- function(input, output) {
    
    OPw <- reactiveValues()
    observeEvent(input$Go, {
        
        if(input$EF){
            showModal(modalDialog("Loading... Please Wait", footer=NULL)) 
            OPw$LIST1 <- X(5,10,20)
        }
        removeModal() 
    })
    
    output$GraphEF <- renderPlot({ 
        OPw$LIST1[[1]]
    },height = 550, width = 700)
    
    output$EFWeightsTable <- renderTable({ 
        OPw$LIST1[[2]]}, colnames = TRUE
    )
    
    #Function
    X <- function(a,b,c){
        PLOT1 <- plot(c(1,2),c(3,4), type="l")
        DF1 <- data.frame(c(1,2),c(3,4))
        
        return(list(c(PLOT1,DF1)))
    }
        
}

shinyApp(ui = ui, server = server)

非常感谢您的帮助,谢谢

【问题讨论】:

  • plot 没有返回值。 return(list(PLOT1,DF1))。您不需要在两者之间使用c,您将获得NULL 用于plot
  • 我的意思是,如果你创建一个对象out &lt;- plot(1, 1); out NULL,plot 是没有返回值的,所以它是NULL。我之前的评论是关于以正确的方式创建列表,即list(PLOT1, DF1) 而不是c(PLOT1, DF1) - (这导致将'DF1'的结构更改为列列表而不是data.frame
  • 您可以使用 ggplot 并将其存储为对象,而不是基本 R 图
  • 啊,我明白了。是的,我会尝试使用 ggplot 来代替。我认为也可以存储常规地块。谢谢

标签: r list shiny


【解决方案1】:

您的代码中有一些错误 - 这是使用 Base R Plot 的解决方案。 代码在需要解释发生了什么的地方包含详细的 cmets。

server <- function(input, output) {
  
  OPw <- reactiveValues()
  observeEvent(input$Go, {
    
    if(input$EF){
      showModal(modalDialog("Loading... Please Wait", footer=NULL)) 
      OPw$LIST1 <- X(5,10,20)
    }
    removeModal() 
  })
  
  output$GraphEF <- renderPlot({ 
    OPw$LIST1[[1]]
  },height = 550, width = 700)
  
  output$EFWeightsTable <- renderTable(
    {
      # Here it seem OP use the wrong reference [[1]] where it should be [[2]]
      OPw$LIST1[[2]]
    }, colnames = TRUE
  )
  
  #Function
  X <- function(a,b,c){
    # Base R plot doesn't return a value but will always output to panel plot
    plot(c(1,2),c(3,4), type="l")
    # To save it to object for later use recordPlot() function after plot function
    PLOT1 <- recordPlot()
    DF1 <- data.frame(c(1,2),c(3,4))
    # Here only use list(...) instead of list(c(...))
    # c(...) convert all objects passed to it into vector - you don't want that.
    return(list(PLOT1,DF1))
  }
  
}

这是输出

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-31
    • 2021-06-21
    • 2017-11-15
    • 1970-01-01
    • 2019-11-11
    • 2022-01-15
    • 2018-09-16
    • 1970-01-01
    相关资源
    最近更新 更多