在闪亮的应用程序外部创建反应功能 [英] Create a reactive function outside the shiny app
问题描述
我试图分解我闪亮的应用程序的代码,以提高可读性并使用testthat
包测试某些功能.
I am trying to decompose the code of my shiny app in order to improve readability and to test some functions using the testthat
package.
我想拥有一些文件(例如server_utils.R
),在其中可以编写可以测试的正常"功能,然后使它们具有反应性.
I would like to have some files (for example server_utils.R
) in which I can write "normal" functions that I can test and then make them reactive.
例如,我想在server_utils.R
中添加类似的内容:
For example I would like to have something like this in server_utils.R
:
my_sum <- function(x, y) {
x + y
}
以及类似的应用程序中的内容:
and something like this in the app:
my_sum_reactive(input$x, input$y)
您知道这种行为是否可能吗?
Do you know if a such behavior is possible?
推荐答案
发光的模块可能会帮助您.
Shiny modules is what might help you.
请参阅此处: https://shiny.rstudio.com/articles/modules.html
如您在文章中所读,如果将输入包装在reactive()
函数中,则可以通过所需的功能来传递输入. (请参阅本文编写服务器功能"部分的末尾.)
As you can read in the article the desired functionality to pass in input is possible if you wrap the input in a reactive()
function. (See the end of the "Writing server functions" section of the article).
您将定义my_sum
函数,如下所示:
(请注意,必须将变量a
和b
用作反应堆a()
和b()
,并将结果包装在reactive()
函数中.)
You would define the my_sum
function as follows:
(Note that you have to use the variables a
and b
as reactives a()
and b()
and wrap the result in a reactive()
function.)
my_sum <- function(input, output, session, a, b) {
reactive(as.numeric(a()) + as.numeric(b()))
}
并且可以将其用作:
my_sum_reactive <- callModule(my_sum, "id", reactive(input$a), reactive(input$b))
然后可以用作:
my_sum_reactive()
可复制的示例:
library(shiny)
my_sum <- function(input, output, session, a, b) {
reactive(as.numeric(a()) + as.numeric(b()))
}
ui <- fluidPage({
fluidRow(
selectInput("a", "a", 1:3),
selectInput("b", "b", 1:3),
textOutput("txt")
)
})
server <- function(input, output, session) {
my_sum_reactive <- callModule(my_sum, "id", reactive(input$a), reactive(input$b))
output$txt <- renderText(paste0("The sum is: ", my_sum_reactive()))
}
shinyApp(ui, server)
这篇关于在闪亮的应用程序外部创建反应功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!