ifelse in R

15. March 2016 programming, r 0
ifelse in R

I found a new way to write an if else statement in R.  I get a bit frustrated with the monotony of opening and closing brackets for if statements.  After going through R courses on Coursera and Data Camp, they both teach if structures the same way.  The new function I discovered, ‘if else’, makes writing if statements easier and they take up less space.

The beautiful thing about this statement, is that it is also part of the base R.  Below is some code that I wrote that checks two variables in a data frame and creates a new variable (column) Val to show whether variable a is less than variable b.

ifelse syntax:

ifelse(condition, true, false)

ifelse example:

# Setup some variables with numbers
a <- (1:10)
b <- c(1,4,2,7,8,2,2,1,3,43)

# Push them to a data frame
df <- data.frame(a,b)

# Use ifelse to check the values
# Loop through each row in the data frame and calculate whether a is < b
for (i in 1:nrow(df)) {
 ifelse(df$a[i] < df$b[i], df$Val1[i] <- "LT", df$Val1[i] <- "GT")

Data Frame results:

screenshot of data frame shown results using the ifelse statement.

If…else syntax

if (condition) {
    do something
} else {
    do something else 

The other way to do it using the if…else syntax:

for (i in 1:nrow(df)) {
 if (df$a[i] < df$b[i]) {
 df$Val2[i] <- "LT"
 } else {
 df$Val2[i] <- "GT"

Leave a Reply