R - If / ifElse

Card Puncher Data Processing

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)





Discover More
Card Puncher Data Processing
R - Flow (Control Structure)

See The Control structures are primarily useful for writing programs. In the console, the apply functions (apply, sapply, ..) are most appropriated. if: testing a condition for: execute a loop n...



Share this page:
Follow us:
Task Runner