简体   繁体   中英

Storing consecutive values from a function to a vector?

I've been messing around learning functions to calculate homework answers (in this case the present value of money) and I've run into a bit of an issue.

Here's the code:

pv <- function(x,y,z) {
   list2 <- 0
   ans <- 0
   for(t in z){
     fv <- x
     d <- y
     rate <- (1+d)^t
     ans[t] <- fv/rate
   }
   return(ans)
 }

To calculate present value I want to apply the function to one value for a range of years (z=1:10, say) and have the value for each year stored in a vector. What I have works, but this strategy breaks down in other applications. For example, when I want to input a vector of values (I have another function where I run the ans vector through a function) for a range of years I have trouble getting back a usable vector.

pv = function(fv, d, t)
  fv/(1+d)^t

pv(1.05^2, 0.05, c(1, 2))

Here's an explanation. Basically, in R, algebraic functions are applied automatically over numeric data, such that looping is often unnecessary.

I had to make a change in your for loop, then I used mapply :

 pv <- function(x,y,z) {
       list2 <- 0
       ans <- 0
       for(t in 1:z){ # changed from t in z
         fv <- x
         d <- y
         rate <- (1+d)^t
         ans[t] <- fv/rate
       }

   return(ans)
 }

mapply(pv, c(1000, 1200, 1500, 5600), c(.05, .02, .03, .09), 5)

Output:

        [,1]     [,2]     [,3]     [,4]
[1,] 952.3810 1176.471 1456.311 5137.615
[2,] 907.0295 1153.403 1413.894 4713.408
[3,] 863.8376 1130.787 1372.712 4324.227
[4,] 822.7025 1108.615 1332.731 3967.181
[5,] 783.5262 1086.877 1293.913 3639.616

Each row contains the present value for each value of x for a period ie row 1 is the present value for 1st period. If you wanted just the 5th period for all values in question:

mapply(pv, c(1000, 1200, 1500, 5600), c(.05, .02, .03, .09), 5)[5,]

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