r-RShiny有条件地显示图



在使用研究ID登录后,我构建了一个RShiny Dashboard来显示参与者自己的ESM研究数据。参与者可以选择他们想在ESM研究中监测的主题,因此并非所有参与者都有所有变量的数据。

在他们的个人仪表板中,我只想显示他们有数据的变量的图表。如果没有数据,则列为NA,并且我希望显示图像而不是绘图。

我不会在这里分享整个代码,只分享相关的部分。这是我尝试过的代码:

在ui部分

fluidRow(  
box(
title = "Zingeving en voldoening", status = "success", solidHeader = TRUE, width = 4, collapsible = TRUE,
if(diarydata_compliance[which(diarydata_compliance$ID == IDnum()),zingeving_selected] == 1) {
plotOutput("plot_zingeving")

} else {
imageOutput("logo_POP")
}
))

然后,在服务器部分定义输出:

##ImageBox "LOGO_POP"
output$logo_POP = renderImage({
return(list(src = "~/Diary Enik Test/fig_output/logo_POP_transparant.png", 
deleteFile = FALSE,
width = "200",
height = "200"))

}) #End renderImage
##Output: Plot Zingeving en Voldoening
#diarydata_themes[which(diarydata_themes$ID == IDnum()),] makes sure that only data is included from the participant with the entered ID.
output$plot_zingeving = renderPlot({
ggplot(diarydata_themes[which(diarydata_themes$ID == IDnum()),], mapping = aes(x = zingeving_voldoening)) + 
geom_bar(aes(fill = Enik_dich),
position = "dodge") +
labs(x = "Heb je dingen gedaan die belangrijk zijn?",
y = "") +
scale_fill_manual(values = c("Bij Enik geweest" = "#6eb76e",
"Niet bij Enik geweest" = "#e98357")) +
theme(legend.text = element_text(size = 14),
legend.title = element_blank(),
axis.text = element_text(size = 14),
axis.title = element_text(size = 14),
legend.position = "top")

})#end renderPlot

当我运行它并尝试启动应用程序时,我会收到一个错误:错误:!没有活动的反应上下文,不允许操作。•你试图做一些只能在被动消费者内部完成的事情。

起初,我在ui部分没有if条件的情况下构建了Shiny应用程序:然后绘图显示正确。只是,当没有绘图变量的数据时,它仍然显示了带有NA的绘图;Zingeving en voldoening";。我想用一张图片代替它。

有人能帮我吗?

由于您试图在box()调用UI中引用IDnum(),因此会出现该错误。相反,使用uiOutput,在服务器中,根据IDNum((更改该UI元素的内容

  1. 所以这是ui的更改
fluidRow(  
box(
title = "Zingeving en voldoening", status = "success", solidHeader = TRUE, width = 4, collapsible = TRUE,
uiOutput("cond_output")
)
)
  1. 以下是您需要在服务器中添加的更改类型
output$cond_output <- renderUI({
if(diarydata_compliance[which(diarydata_compliance$ID == IDnum()),zingeving_selected] == 1) {
plotOutput("plot_zingeving")
} else {
imageOutput("logo_POP")
}
})

因此,您的条件语句现在在renderUI()中进行求值;如果满足条件语句,则cond_output元素变为plotOutput,但如果不满足,则变为imageOutput

最新更新