R - If / ifElse

About

See

?Control

If you want a:

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

Type

if

With one value

Syntax

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

where:

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 } 

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)

Powered by ComboStrap