【发布时间】:2020-06-29 06:13:49
【问题描述】:
这是我在here 发的帖子的后续帖子。最初的问题要求用户在一些文本框/数字框中输入一些值,计算一些函数,然后在数据框中显示结果。
可以使用以下 R 代码(其中还包括我还想添加的 ggplot2 图)来计算它。
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"
)
df <- data.frame(C, P, Seq) # create the data frame for the ggplot and Shiny output
df %>% # plot that data frame
ggplot(aes(x = Seq)) +
geom_line(aes(y = C)) +
geom_line(aes(y = P))
我想在 Shiny 中创建相同的 ggplot - 反应图。我拥有的闪亮代码如下。
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),
tableOutput("S_K_Output")
)
)
#######################################################################
ui <- dashboardPage(header, sidebar, body)
#######################################################################
server <- function(input, output) {
output$S_K_Output <- renderTable({
Seq <- seq(from = input$KInput - 1, to = input$KInput + 1, by = 0.25) # create a sequence going from K-1 to K+1
C <- someFunction(
S = input$SInput,
K = Seq, # Apply this sequence to the function
type = "C"
)
P <- someFunction(
S = input$SInput,
K = Seq,
type = "P"
)
data.frame(C, P, Seq) # Extract the results and put side-by-side
})
}
shinyApp(ui, server)
上面的 Shiny 代码可用于生成表格,但我也想包含情节。我发现这很困难,因为上面的代码将结果输出到 renderTable({}) 函数中(即返回 HTML 表并简单地添加 ggplot 代码不起作用。)
我已经尝试renderPlot 并再次将以上所有代码从renderTable 粘贴到同一个函数中,但我不想重复不必要的计算。所以我的问题是如何将data.frame(C, P, Seq) 从两个不同的renderTable 和renderPlot 导出为ggplot2 图形?我可以在代码的fluidPage 部分的tableOutput 下方添加tablePlot,但我无法获得结果。
【问题讨论】: