闪亮应用中的图像输出

时间:2018-05-30 12:38:47

标签: r shiny shiny-server

我正在尝试将图片包含在闪亮的应用中。我想:"如果它是类型1的情节"这个图像",如果它是0型情节"这是另一个图像"。我知道我必须把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)

1 个答案:

答案 0 :(得分:7)

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

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

其次,要输出图像,您应将它们放在www目录中,请参阅here。然后,我们可以使用renderUIUIOutput创建一个ui元素,我们使用eventReactive myval()的值来选择要显示的图像。

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

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

希望这有帮助!

enter image description here

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)
相关问题