Home > Software design >  Strange behavior of if() inside map() in R
Strange behavior of if() inside map() in R

Time:05-10

Using map() I wrote a simple function that was supposed to return 'yes' if x is 1, 'no' if x is 2, 'maybe' if x is 3.

map(
  .x = c(1,2,3),
  .f = function(x) {
    if (x==1) y= 'yes'
    if (x==2) y='no'
    if (x==3) y='maybe'})

I expected to get a list with 'yes', 'no', 'maybe', yes I got:

[[1]]
NULL

[[2]]
NULL

[[3]]
[1] "maybe"

So it seems that every if() is evaluated and only the last one is returned, which is NULL when x is 1 or 2. My question is why? I would expected if() to behave like in the global environment:

x = 1
    if (x==1) y='yes'
    if (x==2) y='no'
    if (x==3) y='maybe'})
y
[1] "yes"

CodePudding user response:

You're assigning a new value to y three times. Use else to keep make it one expression.

map(
  .x = c(1,2,3),
  .f = function(x) {
    if (x==1) y = 'yes'
    else if (x==2) y = 'no'
    else if (x==3) y = 'maybe'})

#[[1]]
#[1] "yes"
#
#[[2]]
#[1] "no"
#
#[[3]]
#[1] "maybe"

CodePudding user response:

R is an expressions-based language. Expressions have value. (Almost) everything is an expression. Meaning everything ultimately has one value. The function body in the map ends up only having one value, the last if-statement.

So add else, e.g.


map(
  .x = c(1, 2, 3),
  .f = function(x) {
    if (x == 1)
      y = 'yes'
    else if (x == 2)
      y = 'no'
    else if (x == 3)
      y = 'maybe'
  }
)
  • Related