[英]Shiny: How to take a “reactive input” generated from renderUI as input in a function?
[英]How to use an input created in renderUI into a reactive function in R Shiny?
我在 UI 中創建了幾個兩個輸入:“slider0”和“slider1”,在服務器中使用 renderUI“slider2”創建了一個。 我正在嘗試根據 slider0 上的條件語句以及 slider1 和 slider2 的值來計算數據框的新列。
我有以下可重現的代碼:
library(shiny)
library(DT)
library(dplyr)
library(shinydashboard)
library(htmltools)
library(shinyjs)
first_column <- c("15", "25")
second_column <- c("0.5", "50")
d0 <- data.frame(first_column, second_column)
d0[,1:2 ] <- sapply(d0[ ,1:2],as.numeric)
######################### header ##########
header <- dashboardHeader(
title = "TEST")
################ Sidebar ################
sidebar <- dashboardSidebar(
sidebarMenu(
menuItem("Test", tabName = "Test"),
menuItem("Test2", tabName = "Test2")
)
)
######################### body ##################
body <- dashboardBody(
tabItems(
tabItem(tabName = "Test",
fluidRow(
column(width = 4,
box(width = NULL, solidHeader = TRUE,
useShinyjs(),
radioButtons(
inputId="slider0",
label="slider0",
choices = c("Yes"="Yes", "No"="No"), inline=TRUE),
column(4,numericInput("slider1", "slider1", min = 0, max = 1, value = 0.25, step=0.05)),
column(4, uiOutput("slider2"))
)),
column(width = 8,
box(width = NULL, solidHeader = TRUE,
DT::dataTableOutput(outputId = "mytable")
))
))))
################# ui #############
ui<- dashboardPage(
header,
sidebar,
body
)
################server ###############
server <- function(input, output) {
output$slider2 <- renderUI({
req(input$slider1)
numericInput("slider2", "slider2", min = 0, max = 1 , value = 1- input$slider1, step=0.05)
})
############ This code does not have warning error when input$slide1 is used in mutate ##########
d1<-reactive({
if(input$slider0 == "Yes"){
d0 %>%
mutate(C3= first_column*input$slider2)
} else {d0 }
})
output$mytable = renderDataTable({
d1()
})
}
#####
shinyApp(ui=ui, server=server)
在服務器中,我想通過將數據框的一列與服務器中使用 renderUI 定義的 input$slider2 相乘來計算新的 C3 列。
我收到以下錯誤消息:“警告:錯誤: mutate()
輸入C3
的問題。x 輸入C3
不能回收到大小 2。ℹ 輸入C3
是first_column * input$slider2
輸入C3
必須是大小 2或 1,而不是 0。 138:“
當我選擇在 UI 中定義的 input$slider1 時,我沒有任何錯誤/警告消息,但我不知道問題出在哪里。
在進一步使用之前,您可以要求input$server2
req
定義並具有有效值:
d1 <- reactive({
if(input$slider0 == "Yes"){
# Make sure that input$slider2 is ready to be used
req(input$slider2)
# Will be executed as soon as above requirement is fulfilled
d0 %>%
mutate(C3= first_column*input$slider2)
} else {d0 }
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.