Rtist
Rtist

Reputation: 4205

Updating a vector outside the loop in map(), using R

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() ?

Upvotes: 2

Views: 148

Answers (2)

Aron Strandberg
Aron Strandberg

Reputation: 3080

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

Upvotes: 2

Ma&#235;l
Ma&#235;l

Reputation: 51914

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

Upvotes: 1

Related Questions