Roman
Roman

Reputation: 27

Return result from multiple if statements

I'm trying to use multiple actions in if statement. For example:

x <- 1

if (x == 1) {
   paste("First")
   1*1                    #multiple actions
 } else if (x == 2) { 
   paste("Second")
   2*2 } else {("Nothing")
 }

 [1] 1        #what I'm getting

 [2] "First"
      1       #what I want to get

In this case only the second part of the expressions was printed to the console. Any ideas how can I run all actions between if and else if ?

Upvotes: 0

Views: 97

Answers (2)

Nathan Werth
Nathan Werth

Reputation: 5283

All statements are running as intended. The value of a statement is only printed to the console if all these conditions are true:

  • The value isn't saved to a variable
  • The value isn't invisible
  • It's the result of the last statement in an expression
  • R is running in interactive mode

The reason things sometimes print is to help people interactively exploring data in the command line. Instead of type print(x), they can save a few keystrokes by just typing x. In summary, use print if you want to be sure it's printed:

x <- 1

if (x == 1) {
  print("First")
  print(1*1)
} else if (x == 2) {
  print("Second")
  print(2*2)
} else {
  invisible("Nothing")
}
# [1] "First"
# [1] 1

Upvotes: 3

pogibas
pogibas

Reputation: 28379

You can use print or cat:

getResult <- function(x = 1) {
    if (x == 1) {
        cat("First", 1 * 1, "\n")
    } else if (x == 2) { 
        print("Second")
        print(2 * 2)
    } else {
        cat("Nothing\n")
    }
}


getResult()
# First 1 

getResult(2)
# [1] "Second"
# [1] 4

Upvotes: 2

Related Questions