# Create a vector iteratively with conditional

Hi guys, I have a very straightforward question:

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
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

for (i in seq_along(1:30)) {

if (i %% threshold == 0) {

}

}

``````

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`

Not sure how well I understand, but

``````add1 = 1
threshold = 5

x <- c()
x <- 1

for (i in 2:30) {
if (i <= threshold) {
} else {
}
}
``````

and then seems ok:

``````> x
   1   2   3   4   5   9  13  17  21  25  29  33  37  41  45  49  53  57  61
  65  69  73  77  81  85  89  93  97 101 105

> diff(x)
 1 1 1 1 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4

``````

cheers
Fer

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.

``````add1 <- 1
threshold <- 5

input_vec <- 1:20

print(input_vec)
#>    1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20

output_vec <- vector("numeric", length(input_vec))

for (i in seq_along(input_vec)) {
if (i == 1) {
output_vec[[i]] <- input_vec[[i]]
} else if (i %% threshold == 0) {
output_vec[[i]] <- output_vec[[i - 1]] + add2
} else {
output_vec[[i]] <- output_vec[[i - 1]] + add1
}
}

print(output_vec)
#>    1  2  3  4  8  9 10 11 12 16 17 18 19 20 24 25 26 27 28 32
``````

Created on 2020-10-05 by the reprex package (v0.3.0)

2 Likes

Many thanks to both of you!!! Now my next challenge is being able to do it with `purrr` haha.

This solved my issue, once again, thank you so much!! This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.