My goal is to create a vector where the next value is equal to last value + a constant (call this add1). However, when we get to a certain length (call this threshold) we change the constant added to another one (call this add2). The vector starts at 1. Thus, for example:
Let: add1 = 1, threshold = 5, add2 = 4. We would have:
x
1 # start at 1
2 # since add1 = 1, add 1 to last value
3 # since add1 = 1, add 1 to last value
4 # since add1 = 1, add 1 to last value
8 # since threshold = 5, and this is the 5th position, add `add2 = 4` to last value
9
10
11
12
16 # since this is the 10th position (a multiple of `threshold`), add 4 to last value.
So far, I've tried this, but it doesn't work:
x <- c()
x[1] <- 1
for (i in seq_along(1:30)) {
if (i %% threshold == 0) {
x[i+1] <- x[i] + add2
}
x[i+1] <- x[i] + add1
}
I'd love to do this with a map_* function, but I can't even do it with a for loop... let alone doing it with purrr
Good solution Fer, but if I understand the problem correctly, the OP wants to add add2 at every multiple of the threshold index. In the example above, 4 should be added at every 5th, 10th, 15th... index.
Just a small modification to your solution will give the desired result. I would also pre-allocate the result vector beforehand to make the loop more efficient.