Home > Mobile >  Is there a "next" equivalent in map() [R]
Is there a "next" equivalent in map() [R]

Time:02-08

When using for example a for loop I can use next to skip a certain item:

    if (i == 5) next
    print (i)

Is there a similar way to do this in a map() or more specifically in a pmap()?

a <- c(1,2,3)
b <- c(1,1,1)
c <- c(2,2,2)

mapped <- pmap(list(a,b,c),
               function(a,b,c){
                # if (a == 2) next
                print( a   b - c)
               })

Thank you for your help!

########## Edit for formatting of my follow up question to Konrad: Is there any way to avoid getting a NULL element in the list when using if (a != 2)?

a <- c(1,2,3)
b <- c(1,1,1)
c <- c(2,2,2)

mapped <- pmap(list(a,b,c),
               function(a,b,c){
                 if(a != 2){
                 a   b - c
                 }
               })

str(mapped)

returns

#List of 3
 #$ : num 0
 #$ : NULL
 #$ : num 2

But for my solution I would need

#List of 2
 #$ num 0
 #$ num 2

CodePudding user response:

No, the design of map and pmap is that they apply the function to every element. If you want to skip one, then skip it on the input:

library(purrr)
a <- c(1,2,3)
b <- c(1,1,1)
c <- c(2,2,2)
keep <- a != 2

mapped <- pmap(list(a[keep], b[keep], c[keep]),
               function(a,b,c){
                 a   b - c
               })

str(mapped)
#> List of 2
#>  $ : num 0
#>  $ : num 2

Created on 2022-02-08 by the reprex package (v2.0.1.9000)

You can also use purrr functions to do the initial filtering, but I'll leave that to you.

CodePudding user response:

So if you don't want to perform the action for a == 2 can you do:

mapped_two <- pmap(list(a, b, c),
                   function(a, b, c) {
                       if (a != 2) {
                           print(a   b - c)
                       }
                   })

or more explicitly

mapped_three <- pmap(list(a, b, c),
                   function(a, b, c) {
                       if (a == 2) {
                           # Do nothing
                       } else {
                           print(a   b - c)
                       }
                   })

which gives you the same thing

all.equal(mapped_two, mapped_three)
# TRUE
  •  Tags:  
  • Related