【发布时间】:2020-10-18 22:02:13
【问题描述】:
我正在尝试开发一个应用程序,它会询问用户一些值,将这些值传递给函数并将结果输出到 Shiny 中的表格。
我的 R 代码如下:
someFunction <- function(S, K, type){
# call option
if(type=="C"){
d1 <- S/K
value <- S*pnorm(d1) - K*pnorm(d1)
return(value)}
# put option
if(type=="P"){
d1 <- S*K
value <- (K*pnorm(d1) - S*pnorm(d1))
return(value)}
}
SInput <- 20
KInput <- 25
Seq <- seq(from = KInput - 1, to = KInput + 1, by = 0.25)
C <- someFunction(
S = SInput,
K = Seq,
type = "C"
)
P <- someFunction(
S = SInput,
K = Seq,
type = "P"
)
cbind(C, P)
这给了我:
C P
[1,] -3.190686 4.00
[2,] -3.379774 4.25
[3,] -3.567795 4.50
[4,] -3.754770 4.75
[5,] -3.940723 5.00
[6,] -4.125674 5.25
[7,] -4.309646 5.50
[8,] -4.492658 5.75
[9,] -4.674731 6.00
我想使用 Shiny 将其输出为表格。我目前拥有的是:
library(shiny)
library(shinydashboard)
#######################################################################
############################### Functions #############################
someFunction <- function(S, K, type){
# call option
if(type=="C"){
d1 <- S/K
value <- S*pnorm(d1) - K*pnorm(d1)
return(value)}
# put option
if(type=="P"){
d1 <- S*K
value <- (K*pnorm(d1) - S*pnorm(d1))
return(value)}
}
############################### Header ###############################
header <- dashboardHeader()
#######################################################################
############################### Sidebar ###############################
sidebar <- dashboardSidebar()
#######################################################################
############################### Body ##################################
body <- dashboardBody(
fluidPage(
numericInput("SInput", "Input S:", 10, min = 1, max = 100),
numericInput("KInput", "Input K:", 10, min = 1, max = 100),
verbatimTextOutput("S_K_Output")
)
)
#######################################################################
ui <- dashboardPage(header, sidebar, body)
#######################################################################
server <- function(input, output) {
output$S_K_Output <- observeEvent(
input$Seq <- seq(from = input$KInput - 1, to = input$KInput + 1, by = 0.25), # create a sequence going from K-1 to K+1
input$C <- someFunction(
S = input$SInput,
K = input$Seq, # Apply this sequence to the function
type = "C"
),
input$P <- someFunction(
S = input$SInput,
K = input$Seq,
type = "P"
),
cbind(input$C, input$P) # Extract the results and put side-by-side
)
}
我收到以下错误:
.getReactiveEnvironment()$currentContext() 中的错误:操作不 允许没有活动的反应上下文。 (你试图做某事 这只能从反应式表达式或观察者内部完成。)
我相信这是因为我试图通过 observeEvent() 传递数据。
我的问题是,如何允许用户输入值、应用函数并将结果显示在表格中?
【问题讨论】:
-
observeEvent并不意味着返回一个值(它主要在副作用中运行)。也许你需要renderText代替? -
当我申请
renderTable和renderText时,我收到相同的错误消息。