我心血來潮寫了一個可以簡易計算儲蓄險的function
require(ggplot2)
#year <- 20 #你要繳納幾年
#restyear <- 40 #繳完後還可以活多久
#yearget <- 12 #一年得到多少錢
#yearpay <- 10 #一年繳多少錢
#rate <- 0.02 #你認為的市場利率
npvplot <- function(yearpay=10,yearget=12,rate=0.02,year=20,restyear=40
){
npv<-function(yearpay=10,yearget=12,rate=0.02,year=20,restyear=40){
benefit<- sum( yearget/ ( (1+rate)^seq(year-1, year+restyear-1) ) )
cost <- sum ( yearpay/ ( (1+rate)^seq(0, year-1 ) ) )
return( benefit-cost )
}
benefit <- vector("numeric",length = 50)
for(i in 1:50){
benefit[i]<- npv(yearpay=10,yearget=12,rate=0.02,year=20,i)
}
restlife <- c(1:50)
dat <- data.frame(restlife,benefit)
qplot(restlife,benefit,geom = "line")
}
npvplot()
這個function會畫出 繳費完後每多活一年,NPV的淨值會如何變化的圖
但是我想把它做成shiny
但是不知道為何沒又error但是畫出來的圖形都是一條水平線
library(plotly)
library(shiny)
library(ggplot2)
ui <- fluidPage(
titlePanel(title=h4("簡易儲蓄險NPV計算()", align="center")),
actionButton("go", "Go"),
numericInput("yearpay", "一年要繳多少錢(萬)", 10),
numericInput("year", "要繳幾年", 20),
numericInput("yearget", "期滿後一年可得的報酬(萬)", 12),
numericInput("restyear", "期滿後預期可活幾年", 40),
numericInput("rate", "你認為的通貨膨脹率", 0.02),
plotOutput("plot")
)
server <- function(input, output) {
npvplot <- function(yearpay,yearget,rate,year,restyear){
npv<-function(yearpay,yearget,rate,year,restyear){
benefit<- sum( yearget/ ( (1+rate)^seq(year-1, year+restyear-1) ) )
cost <- sum ( yearpay/ ( (1+rate)^seq(0, year-1 ) ) )
return( benefit-cost )
}
benefit <- vector("numeric",length = 50)
for(i in 1:50){
benefit[i]<- npv(yearpay,yearget,rate,year,i)
}
restlife <- c(1:50)
dat <- data.frame(restlife,benefit)
return(dat )
#qplot(restlife,benefit,geom = "line")
}
value<- eventReactive(input$go, {
npvplot(input$yearpay,input$year,input$yearget,input$restyear,input$rate)
})
output$plot <- renderPlot({
ggplot(value(),aes(x=restlife,y=benefit))+geom_line()
})
}
shinyApp(ui, server)
想請問各位大神是哪裡出錯了
附上改正 https://pastebin.com/K6NA8DUL
目前是local可以動 但是無法發布 出現 error