How to use apply function with a moving window?


#1

All,
I am trying to calculate xnpv for a vector of cash flow and dates.
I would like to do so using the apply function implementing a moving
window. To elaborate further:

i <- 0.01
cf <- c(-1,0.5,0.9,1.2,1.5)
d <- as.Date(c("2015-01-01", "2015-02-15",
"2015-04-10","2015-05-01","2015-07-01"))
Res <- vector()
for(i in 1:length(d))
{
    Res <- c(Res,xnpv(i,cf[i:length(cf)],d[i:length(d)]))
}

I am able to achieve what I want using the for loop show above - however,
I would like to be able to do this using a function from the apply family.


#2

Below are a couple of ways to do this.

It really would help if you used a reprex for the code examples you post here. As is the quotes in your example cannot be copy pasted without hand editing. Also we have no way to be able to tell what packages your code depends on… although in this case its easy to figure it out.

Using a reprex just makes it easier for us to help you. Here is a link to using reprex.

https://www.tidyverse.org/help/

suppressPackageStartupMessages(library(tidyverse))
suppressPackageStartupMessages(library(tvm))
i <- 0.01
cf <- c(-1,0.5,0.9,1.2,1.5)
d <- as.Date(c("2015-01-01", "2015-02-15",
                                "2015-04-10","2015-05-01","2015-07-01"))
Res <- vector()
for(i in 1:length(d))
{
    Res <- c(Res,xnpv(i,cf[i:length(cf)],d[i:length(d)]))
}

#use tidyverse
# Once you get used to the tidyverse you may find
# it easier to use than the base functions
Res2 <- 1:length(d) %>% map_dbl(~ xnpv(., cf[.:length(cf)], d[.:length(d)]))

identical(Res, Res2)
#> [1] TRUE

# use lapply
Res3 <- lapply(1:length(d), function(i) {
    xnpv(i,cf[i:length(cf)],d[i:length(d)])
})

identical(Res, unlist(Res3))
#> [1] TRUE