Home > Software engineering >  Updating a vector outside the loop in map(), using R
Updating a vector outside the loop in map(), using R

Time:05-02

I have the following simple vector:

a = c(1,0,0,1,0,0,0,0)

and I would like to obtain a vector (b) such that for each indicator x in a, if a[x] is 1, we let it as is, and if it is 0, we compute a[x-1] 1, until the next 1:

b = c(1,2,3,1,2,3,4,5) 

I tried using map():

map(
  .x = seq(1,(length(a))),
  .f = function(x) {
    a[x] = ifelse(a[x]==1, a[x], a[x-1] 1)
    a})

Obviously this does not work because map does not update the a vector. How can I do this using map(). Is it even possible to update a something outside map() ?

CodePudding user response:

If you just change it to use the superassignment operator <<-, the way you attempted it does in fact work.

a = c(1,0,0,1,0,0,0,0)

map(
  .x = seq(1,(length(a))),
  .f = function(x) {
    a[x] <<- ifelse(a[x]==1, a[x], a[x-1] 1)
    a})
a

#> [1] 1 2 3 1 2 3 4 5

CodePudding user response:

Maybe a solution close to what you're looking (i.e. that would mimic a for loop) for is purrr::accumulate.

accumulate(1:8, .f = ~ ifelse(a[.y] == 1, 1, .x   1))
#[1] 1 2 3 1 2 3 4 5
  • Related