-1

I have written the following function in R with two sequential if conditions:

f <- function(a) {
  if (a > 10) {
  c <- 'a is greater than 10'
  c
  }
  if (a < 10) {
  c <- 'a is less than 10'
  c 
  } 
}

Calling f(1) returns 'a is less than 10', however, calling f(11) returns nothing.

I am confused as to why this happens? The two sequential if statements should in theory have the same effect as an if-else statement, however, if the second condition is triggered instead of the first, no output is returned. I have tried multiple variations of this function, and the same effect is still observed. Any help would be appreciated!

franiis
  • 1,378
  • 1
  • 18
  • 33
DLim
  • 93
  • 5

1 Answers1

0

In R function returns anything that is returned by last call in this function (or by return).

In your example if a < 10 then is returned c (as expected). But if condition a < 10 is false, then last call is if condition - so nothing is returned.

You can try this to achieve your results:

f <- function(a) {
  if (a > 10) {
    c <- 'a is greater than 10'
    print(c)
  }
  if (a < 10) {
    c <- 'a is less than 10'
    print(c) 
  } 
}
f(1)
f(11)
franiis
  • 1,378
  • 1
  • 18
  • 33
  • Hi franiis, thanks for your reply. Does this mean that if conditions actually return something even if they are not triggered? – DLim Aug 14 '18 at 09:44
  • Great question. I checked it to be sure and yes. It returns `NULL`. You can use this to check it: `ff <- function() { return(if (1>2) {10})} ; a <- ff() ; a` – franiis Aug 14 '18 at 09:49