Reputation: 37
I'm new to R and I need help creating a vector sequence in R using an initial starting element, and calculating the next next element in the vector sequence based off of the previous vector element.
Here is what I want to do. The first element (z) of the vector is going to be defined as:
z = (X * Y) + X
So if X = 100, Y = 0.14, then Z = 114.
I then want to take that new z and call it x for the time we calculate. So then the cycles repeats, with y staying constant, and 114 become the new x value.
So Z =(114, 129.96, 148.15, ...) and so on.
I had thought some combination of seq()
and rollapply()
would work, but I'm yet to figure it out. I'm working with data frames, and this is small part of more complex calculation I'm trying to perform.
Any help would be appreciated.
Thanks!
Upvotes: 1
Views: 357
Reputation: 3634
If you want to be cool, nonloopy, and more generalizable:
value = 114
nout <- 10
y <- .14
v <- Reduce(function(v, x) y*v +v, x=numeric(nout), init=value, accumulate=TRUE)
[1] 114.0000 129.9600 148.1544 168.8960 192.5415
[6] 219.4973 250.2269 285.2586 325.1949 370.7221
But given your use case, a for
loop would also work fine, and is more readable:
X <- 100
Y <- .14
z <- rep(NA, 10)
z[1] <- (X * Y) + X
for(i in 2:length(z)){
z[i] <- (z[i-1] * y) + z[i-1]
}
z
[1] 114.0000 129.9600 148.1544 168.8960 192.5415
[6] 219.4973 250.2269 285.2586 325.1949 370.7221
Upvotes: 2
Reputation: 145755
Let's do a little math:
z = x * y + x
= x * (y + 1)
So your sequence is
x,
x * (y + 1),
x * (y + 1) * (y + 1), ...
Which is to say
z_i = x * (y + 1) ^ (i - 1)
Since all the arithmetic operations in R are vectorized, including ^
, this is simple to code:
x = 100
y = 0.14
x * (y + 1) ^ (0:10)
# [1] 100.0000 114.0000 129.9600 148.1544 168.8960 192.5415 219.4973 250.2269 285.2586
# [10] 325.1949 370.7221
No loops or fancy functions needed. You can replace 10
in my code by however many iterations you'd like.
Upvotes: 2
Reputation: 2137
You could write a for loop:
# Starting values
x <- 100 + 14
y <- .14
z <- 114
# For loop with 100 iterations:
for(i in 2:100) {
z[i] <- (x * y) + x
x <- z[i]
}
All calculated values will be stored in z.
Upvotes: 1