R - If / ifElse

> Procedural Languages > R

1 - About

See

?Control

If you want a:

  • Scalar operation (over one value): use the if statement
  • Vectorial operation (over multiple value): use the ifelse

3 - Type

3.1 - if

With one value

3.1.1 - Syntax

if(cond) expr
if(cond) cons.expr  else  alt.expr

where:

Advertising

3.1.2 - Example

  • Without return value
if(1>2) {
    print("1>2")
} else if(FALSE) {
    print (FALSE)
} else {
    print("2>1")
}
  • With return value (Conditional Assignment)
x = if(4 > 3) { 1 } else { 0 } 

3.2 - ifelse

If else takes vectors as input and return vector on output

  • With the data frame df, when the TOTAL_TIME_SEC is above 200, give it the value 200.
df$TOTAL_TIME_SEC_CAPPED <-  ifelse(df$TOTAL_TIME_SEC > 200, 200, df$TOTAL_TIME_SEC)
lang/r/if.txt · Last modified: 2017/05/12 11:18 by gerardnico