Home > other >  Writing a Function to Iterate a single Row by 1:n sequence in R
Writing a Function to Iterate a single Row by 1:n sequence in R

Time:10-26

I'm trying to write a function which will take a given number, n, and successively assign the values from the defined sequence, 1:n, to my formula. My current code below, gives me an error saying: numerical expression has 2 elements: only the first usednumerical expression has 8 elements: only the first used[1]. What I'm trying to do is plug each individual value from my sequence (1:n) into my formula and then sum each individual result.

`

df<-data.frame(Acct=c("A","B"),par=c(1000,1000),cpnA=c(30,30),n=c(8,8),y=c(0.025,0.025))

pvcf<-function(data,cpnA,n,par,yield){
i <- 1:(n)
cf<-c(rep(cpnA,n-1),par cpnA)
pv<- sum(cf/(1 y)^(1:i))
return(pv)
}

pvcf(df,df$cpnA,df$n,df$par,df$y)

` The issue I think I'm running into is the fact that I have different "Accts" (multiple rows). If I only have a single Acct my code works by simply using this code:

df<-df%>%filter(Acct=="A")
cf<-c(rep(df$cpnA,df$n-1),df$par df$cpnA)
pv<-sum(cf/(1 df$y)^(1:df$n))

Based on other posts similar to mine, my issue may also be the way I define my i variable. Do I need to use a for loop if I'm dealing with multiple, distinct, rows?

CodePudding user response:

I don't really understand, but maybe you are looking for such a solution

df <-
  data.frame(
    Acct = c("A", "B"),
    par = c(1000, 1000),
    cpnA = c(30, 30),
    n = c(8, 8),
    y = c(0.025, 0.025)
  )

pvcf <- function(cpnA, n, par, yield) {
  i <- 1:n
  cf <- c(rep(cpnA, n - 1), par   cpnA)
  pv <- sum(cf / (1   yield) ^ i)
  return(pv)
}


purrr::pmap(df[-1], pvcf)
#> [[1]]
#> [1] 1035.851
#> 
#> [[2]]
#> [1] 1035.851

Created on 2021-10-25 by the reprex package (v2.0.1)

or

mapply(FUN = pvcf, n = df$n, par = df$par, yield = df$y, cpnA = df$cpnA)
[1] 1035.851 1035.851
  •  Tags:  
  • r
  • Related