R + map (from purrr): how to introduce condition for early stopping iteration through a list?

40 Views Asked by At

Please have a look at the simple reprex at the end of this post. I use map with a trivial function (it just removes 10) applied to a list of numbers. I wonder if it is possible to introduce somehow a stopping condition in map() from purrr: as soon as the output of the function is negative, I would like purrr to stop cycling through the list.

Of course, there are smarter ways to achieve this result, but I am looking for a way (if it exists) to use map with a stopping condition (as I would do in an old-fashoned loop). Thanks for any advice.

library(tidyverse)



df <- seq(1e2, -30, length=36) |>
    as.list()
    
rem_10 <- function(x){

    res <- x-10
    return(res)
}


dd <- map(df, rem_10 ) ## I would like map to stop as soon as the output of
## appying rem_10 is negative. How to implement a stopping condition so that map does not iterate through all the elements of a list ?


dd
#> [[1]]
#> [1] 90
#> 
#> [[2]]
#> [1] 86.28571
#> 
#> [[3]]
#> [1] 82.57143
#> 
#> [[4]]
#> [1] 78.85714
#> 
#> [[5]]
#> [1] 75.14286
#> 
#> [[6]]
#> [1] 71.42857
#> 
#> [[7]]
#> [1] 67.71429
#> 
#> [[8]]
#> [1] 64
#> 
#> [[9]]
#> [1] 60.28571
#> 
#> [[10]]
#> [1] 56.57143
#> 
#> [[11]]
#> [1] 52.85714
#> 
#> [[12]]
#> [1] 49.14286
#> 
#> [[13]]
#> [1] 45.42857
#> 
#> [[14]]
#> [1] 41.71429
#> 
#> [[15]]
#> [1] 38
#> 
#> [[16]]
#> [1] 34.28571
#> 
#> [[17]]
#> [1] 30.57143
#> 
#> [[18]]
#> [1] 26.85714
#> 
#> [[19]]
#> [1] 23.14286
#> 
#> [[20]]
#> [1] 19.42857
#> 
#> [[21]]
#> [1] 15.71429
#> 
#> [[22]]
#> [1] 12
#> 
#> [[23]]
#> [1] 8.285714
#> 
#> [[24]]
#> [1] 4.571429
#> 
#> [[25]]
#> [1] 0.8571429
#> 
#> [[26]]
#> [1] -2.857143
#> 
#> [[27]]
#> [1] -6.571429
#> 
#> [[28]]
#> [1] -10.28571
#> 
#> [[29]]
#> [1] -14
#> 
#> [[30]]
#> [1] -17.71429
#> 
#> [[31]]
#> [1] -21.42857
#> 
#> [[32]]
#> [1] -25.14286
#> 
#> [[33]]
#> [1] -28.85714
#> 
#> [[34]]
#> [1] -32.57143
#> 
#> [[35]]
#> [1] -36.28571
#> 
#> [[36]]
#> [1] -40

Created on 2024-01-19 with reprex v2.0.2

0

There are 0 best solutions below