antimuon
antimuon

Reputation: 262

Looping through an R vector to apply a formula

I am trying to loop through two vectors and apply a formula to the data but I can't figure out how to do what I want to do...

Basically here is some sample data...two vectors that I need to reference...

v1 <- c(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17)
v2 <- c(0.01,0.06,0.11,0.16,0.21,0.26,0.31,0.36,0.41,0.46,0.51,0.56,0.61,0.66,0.71,0.76,0.81)

This is this the formaula I would like to apply...this would be the first instance...

(1+v2[2])^v1[2] / (1+(v2[1]^v1[1]))

The second iteration would be...

(1+v2[3])^v1[3] / (1+(v2[2]^v1[2]))

So I am trying to do this but I can't figure out how to iterate the vector index...I am trying along the lines of this but I can't increase the index via a counter, e.g., i...

for (i in seq_along(v1) {
    i <- 0
    res[i] <- ((1+v2[2+i])^v1[2+i] / (1+(v2[1+i]^v1[1+i]))
    i <- i+1
}

After going through the loop I would get the following output...

> res
 [1] 1.112475 1.217187 1.323924 1.432501 1.542753 1.654534 1.767715 1.882178 1.997821 2.114550 2.232280 2.350938 2.470454 2.590767 2.711821 2.833564

I have done lots of searching but I am coming up blank, any suggestions?

Upvotes: 0

Views: 51

Answers (1)

Andrew Gustar
Andrew Gustar

Reputation: 18425

You can do this in one go with res <- (1+v2[-1])^v1[-1] / (1+(v2[-17]^v1[-17]))

Basically this uses length-16 vectors (v1 and v2 minus the first and last elements) and takes advantage of R's natural vector processing.

Upvotes: 1

Related Questions