简体   繁体   中英

How to to print a plot based on function arguments in R?

I am trying to build a savings calculator. Eventually, I want to create an RShiny app, but before I do that, I want to make sure the code is perfect. Do what I want to do, I have to use three chunks, which are:

ks <- function (x) { number_format(accuracy = 1,
                                   scale = 1/1000,
                                   big.mark = ",")(x) }
savings <- function(years,apr,initial,investment) {
   value <- numeric(years + 1)
   value[1] <- initial
   for (i in 1:years) value[i + 1] <- (value[i] + investment) * apr
   data.frame(year = 0:years, value)
}
savings(45.02,1.07,45000,15000)
ggplot(data=savings(45,1.07,45000,15000),aes(x=year,y=value))+geom_line()+ scale_x_continuous(breaks = seq(0, 100, by = 5)) +
  scale_y_continuous(labels = ks, breaks = seq(0, 400000000, by = 250000))+labs(x="Year",y="Value (thousands)")

I want to produce the ggplot as part of the "savings" function but I do not know how to integrate it.

You can save the dataframe in an object and use it in ggplot

library(ggplot2)

savings <- function(years,apr,initial,investment) {
   value <- numeric(years + 1)
   value[1] <- initial
   for (i in 1:years) value[i + 1] <- (value[i] + investment) * apr
   df <- data.frame(year = 0:years, value)

   ggplot(data=df,aes(x=year,y=value))+ geom_line() + 
    scale_x_continuous(breaks = seq(0, 100, by = 5)) +
    scale_y_continuous(labels = ks, breaks = seq(0, 400000000, by = 250000)) + 
    labs(x="Year",y="Value (thousands)")
}

savings(45.02,1.07,45000,15000)

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM