我想给输入百分比或值的选项。当用户输入其中一个时,我希望另一个自动填充。
对于代码:
textInput(DownDollars, "Downpayment (Dollars)", value = "", width = NULL, placeholder = NULL),
textInput(DownPercent, "Downpayment (Percent)", value = "", width = NULL, placeholder = NULL)
是否有办法使用这些输入的输出来替代value =
选项?
更新:下面的代码不能使用另一个输入作为参考值:
ui <- fluidPage(
numericInput("HomePrice", "Home Price", value = ""),
numericInput("DownPaymentDollars", "Down Payment (Dollars)", value = "", width = NULL),
numericInput("DownPaymentPercent", "Down Payment (Percent)", value = "", width = NULL)
)
server = function(input, output, session){
#referenceValue <- 254
observeEvent(input$DownDollars, {
updateNumericInput(session, "DownPaymentPercent", value = input$DownDollars * 100 / input$HomePrice)
})
observeEvent(input$DownPercent, {
updateNumericInput(session, "DownPaymentDollars", value = input$DownPercent * input$HomePrice / 100)
})
}
shinyApp(ui, server)
首先,使用numericInput
获取数值更容易。下面的代码可以满足您的需求:
library(shiny)
ui <- fluidPage(
numericInput("DownDollars", "Downpayment (Dollars)", value = "", width = NULL),
numericInput("DownPercent", "Downpayment (Percent)", value = "", width = NULL)
)
server = function(input, output, session){
referenceValue <- 254
observeEvent(input$DownDollars, {
updateNumericInput(session, "DownPercent", value = input$DownDollars * 100 / referenceValue)
})
observeEvent(input$DownPercent, {
updateNumericInput(session, "DownDollars", value = input$DownPercent * referenceValue / 100)
})
}
shinyApp(ui, server)
我定义了一个referenceValue来计算百分比,您可以根据需要定义这个值,例如从另一个用户输入中获取。
注意用引号定义输入id。
编辑
当使用另一个numericInput
获取参考值时,您需要观察这个新的numericInput
来更新计算。两个updateNumericInput
中的一个必须同时被两个observeEvent
触发(参见这篇解释语法的文章):
library(shiny)
ui <- fluidPage(
numericInput("HomePrice", "Home Price", value = ""),
numericInput("DownDollars", "Downpayment (Dollars)", value = "", width = NULL),
numericInput("DownPercent", "Downpayment (Percent)", value = "", width = NULL)
)
server = function(input, output, session){
observeEvent({
input$HomePrice
input$DownDollars
}, {
updateNumericInput(session, "DownPercent", value = input$DownDollars * 100 / input$HomePrice)
})
observeEvent(input$DownPercent, {
updateNumericInput(session, "DownDollars", value = input$DownPercent * input$HomePrice / 100)
})
}
shinyApp(ui, server)