闪亮应用程序中的图像输出

Image output in shiny app

我正在尝试在闪亮的应用程序中包含图像。我想要:"if it is type 1 plot "这张图片",如果它是类型 0 图 "this other image"。我知道我必须将 jpg 文件放入 app.R 所在的文件夹,然后调用它但是不知道怎么办。

这是我一直使用的代码(有效),我只需要在渲染中包含图像。

library(shiny)

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

  # Application title
  titlePanel("Myapp"),

  #Inputs
  dateInput(inputId = "dob", label="Birth"),
  dateInput(inputId = "ad", label="Date"),
  actionButton("Submit", icon("fas fa-magic"), label="Submit"),


  #Outputs
  textOutput(outputId = "textR"),
  imageOutput(outputId = "imageR1"),
  imageOutput(outputId="imageR2")
)



# Define server logic required to draw a histogram
server <- function(input, output) {
  #my output should be named textR and imageR1, imageR2

  observeEvent(input$Submit, 
           output$textR<-renderText({
             v1<-as.numeric(as.Date(input$ad,format="%Y/%m/%d") - as.Date(input$dob, format="%Y/%m/%d"))/30.5
             value_v1<-ifelse(v1>48, "type1", "type2")
             print(value_v1)
           }))

}

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

observeEvent 中定义输出对象是不好的做法。在这种情况下,独立于如何切换图像的选择,我建议使用 eventReactive - 让我们称之为 myval。这创建了一个仅在特定事件发生时才会更改的反应,在本例中为单击提交按钮。然后我们可以在 renderText 语句的主体中引用它,这样就可以简单地变成:

  output$textR<-renderText({
    print(myval())
  })

其次,对于图像的输出,您应该将它们放在www目录中,参见here。然后我们可以用 renderUIUIOutput 创建一个 ui 元素,在其中我们使用 eventReactive myval() 的值到 select 图像显示。

下面给出了一个工作示例。请注意,我将其保存为 app.R,并使用了引用 link 的文件夹结构,因此:

| shinyApp/
    | app.R
    | www/
       | zorro.jpg
       | notzorro.jpg

希望对您有所帮助!


library(shiny)

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

  # Application title
  titlePanel("Myapp"),

  #Inputs
  dateInput(inputId = "dob", label="Birth"),
  dateInput(inputId = "ad", label="Date"),
  actionButton("Submit", icon("fas fa-magic"), label="Submit"),

  #Outputs
  textOutput(outputId = "textR"),
  uiOutput(outputId = "my_ui")
)



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

    myval <- eventReactive(input$Submit,
                         {
                           v1<-as.numeric(as.Date(input$ad,format="%Y/%m/%d") - as.Date(input$dob, format="%Y/%m/%d"))/30.5
                           return(ifelse(v1>48, "type1", "type2"))
                         })

  output$textR<-renderText({
    print(myval())
  })

  output$my_ui<-renderUI({
    if(myval()=='type1')
      img(src='zorro.jpg', height = '300px')
    else
      img(src='notzorro.jpg', height = '300px')
  })

}

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