商业估值随机建模R脚本转换为Shiny应用问题求助
R脚本转Shiny应用实现(商业估值随机建模场景)
实现说明
输入参数
- 模拟次数:对应原脚本lapply遍历的迭代次数,支持自定义调整
- 销售量:不同场景下的产品销售数量,保留原脚本三场景随机采样逻辑
- 售价:不同场景下的产品单位售价,保留原脚本三场景对应规则
- 单位成本:服从三角分布的可变单位成本,默认取值范围5.5-7.5
- 固定成本:生产经营固定支出,默认取值120000
输出内容
- 净利润统计摘要:净利润计算公式为 Net profit = 销售量(售价-单位成本)-固定成本*,输出所有模拟结果的统计指标
- 净利润分布直方图:可视化所有模拟结果的分布特征
完整可运行代码
使用前请先安装triangle包以支持三角分布随机数生成。
library(shiny) library(triangle) # UI定义 ui <- fluidPage( titlePanel("商业估值随机建模工具"), sidebarLayout( sidebarPanel( numericInput("sim_num", "模拟次数", value = 10000, min = 100, max = 100000), numericInput("sc1_sales", "场景1销售量", value = 100000), numericInput("sc1_price", "场景1售价", value = 8), numericInput("sc2_sales", "场景2销售量", value = 75000), numericInput("sc2_price", "场景2售价", value = 10), numericInput("sc3_sales", "场景3销售量", value = 50000), numericInput("sc3_price", "场景3售价", value = 11), sliderInput("unitcost_range", "单位成本三角分布范围", min = 1, max = 20, value = c(5.5,7.5)), numericInput("fixed_cost", "固定成本", value = 120000) ), mainPanel( h3("净利润统计摘要"), verbatimTextOutput("profit_summary"), h3("净利润分布直方图"), plotOutput("profit_hist") ) ) ) # 服务端逻辑 server <- function(input, output) { # 响应式计算净利润 profit_res <- reactive({ sim_n <- input$sim_num res <- lapply(1:sim_n, function(i) { DU <- sample(1:3, size = 1) if(DU == 1) { SalesVolume <- input$sc1_sales SellingPrice <- input$sc1_price } else if(DU == 2) { SalesVolume <- input$sc2_sales SellingPrice <- input$sc2_price } else { SalesVolume <- input$sc3_sales SellingPrice <- input$sc3_price } unitcost <- rtriangle(1, input$unitcost_range[1], input$unitcost_range[2]) fixedcosts <- input$fixed_cost return(SalesVolume * (SellingPrice - unitcost) - fixedcosts) }) unlist(res) }) # 输出统计摘要 output$profit_summary <- renderPrint({ summary(profit_res()) }) # 输出直方图 output$profit_hist <- renderPlot({ hist(profit_res(), main = "净利润分布直方图", xlab = "净利润", col = "lightblue") }) } # 运行应用 shinyApp(ui = ui, server = server)
内容的提问来源于stack exchange,提问作者Sam Returns
相关产品推荐
相关产品推荐

