您好,我是RShiny的新手,我正在尝试为一个项目构建应用程序。
我的UserInterface中有5张图像,我想使它们可点击:当您单击图像时,它将在mainPanel中显示数据框的子集。
我的数据框包含一个名为“ Mood”的列,并且有5种心情(“ Party and Dance”,“ Rap”,“ Happy vibes”,“ Sunday Chillout”和“ Roadtrip音乐”)。每个图像应显示其中一种情绪的行。
这是我现在使用的代码:
UI.R
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%"))
))))
Server.R
目前,我刚刚设法将选择框链接到子集数据框,但是我想摆脱它,而只使用图像。
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)