简体   繁体   English

使用 R 在 map() 循环外更新向量

[英]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),这样对于 a 中的每个指标 x,如果 a[x] 为 1,我们让它保持原样,如果它为 0,我们计算 a[x-1] + 1 ,直到下一个:

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

I tried using map():我尝试使用 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.显然这不起作用,因为 map 不更新 a 向量。 How can I do this using map().我如何使用 map() 来做到这一点。 Is it even possible to update a something outside map()?甚至可以更新 map() 之外的东西吗?

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

Maybe a solution close to what you're looking (ie that would mimic a for loop ) for is purrr::accumulate .也许接近您正在寻找的解决方案(即模拟for loop )是purrr::accumulate

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM