簡體   English   中英

如何使圖像可點擊以顯示子集數據框? (R 閃亮)

[英]How to make images clickable to display a subset Dataframe ? (R Shiny )

您好,我是 RShiny 的新手,我正在嘗試為一個項目構建一個應用程序。

我的用戶界面中有 5 個圖像,我想讓它們可點擊:當您點擊圖像時,它會在 mainPanel 中顯示數據框的一個子集。

我的數據框包含一個名為“情緒”的列,有 5 種情緒(“派對和舞蹈”、“說唱”、“快樂氛圍”、“周日放松”和“公路旅行音樂”)。 每個圖像應顯示其中一種情緒的行。

這是我現在使用的代碼:

用戶界面


shinyUI(

  fluidPage(  useShinyjs(), 

             headerPanel(
               h1(img(src="logo.png",height  = 70, width = 70),"Quelle est votre humeur du moment ?",
                  style = "font-weight: 500; color: #FFFFFF;")),

   dashboardSidebar(
     fluidRow(
       column(width=11.9, align="center",
              selectInput("Mood", label= "Choose your Mood : ", 
                             choices = test$Mood),
                 img(id="my_img1",src="party.jfif",width="19.5%",style="cursor:pointer;"),
                 img(id="my_img2",src="cluster 2.jpg",width="19.5%",style="cursor:pointer;"),
                 img(id="my_img3",src="roadtrip.jpg",width="19.5%",style="cursor:pointer;"),
                 img(id="my_img4",src="rap.jfif",width="19.5%",style="cursor:pointer;"),
                 img(id="my_img5",src="sunday.jpg",width="19.5%",style="cursor:pointer;")),

 column(11.2, align="center",
      mainPanel(br(),br(),DT::dataTableOutput("dynamic"), width = "100%"))
 )))) 

服務器端

現在我剛剛設法將選擇框鏈接到子集數據框,但我想擺脫它而只使用圖像。


shinyServer(function(input,output){

  output$dynamic<- DT::renderDataTable({

  data <- DT::datatable(test[test$Mood ==input$Mood, c("Song","Artist","Mood","Listen to song"), drop = FALSE], escape = FALSE)
  data   

  })
})

我嘗試了很多組合,但都失敗了,因為我沒有 Shinyjs 工作原理的基本技能。

我的最后一次嘗試:(我想為每個圖像手動執行此操作,但它當然不起作用)

shinyServer(function(input,output){
 onclick("my_img1",     { print(datatable(test[test$Mood =="Party and dance", c("Song","Artist","Mood","Listen to song"), drop = FALSE], escape = FALSE))})

})

任何反饋將不勝感激! 謝謝 !

這是我的界面的樣子

我已經有一段時間沒有使用 Shiny 了,所以我可能有點生疏了。 但這里有一種可能的方法來解決您的問題:您可以使用reactiveValue來跟蹤選擇了哪種心情,並在單擊其中一張圖像時更新該變量。 然后使用reactiveValue在子集化你的dataframe ,如下圖所示。 希望這可以幫助!

library(shiny)
library(shinyjs)

df = data.frame(mood = c('mood1','mood1','mood1','mood2','mood2','mood2'), 
                example = c('dog',' cat','bunny','elephant','t-rex','not dog'))

ui <- shinyUI(

  fluidPage(  
    useShinyjs(), 
    img(id="my_img1",src="img1.png",width="19.5%",style="cursor:pointer;"),
    img(id="my_img2",src="img1.png",width="19.5%",style="cursor:pointer;"),
    DT::dataTableOutput("dynamic")
  )
)

server <- shinyServer(function(input,output){


  selected_mood <- reactiveVal()
  shinyjs::onclick("my_img1",  selected_mood('mood1'))
  shinyjs::onclick("my_img2",  selected_mood('mood2'))
  output$dynamic<- DT::renderDataTable({  
    req(selected_mood())
    df[df$mood == selected_mood(),]
  })
})

shinyApp(ui, server)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM