Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
How to write multi-level ifelse() in R?
# How to write multi-level ifelse()
set.seed(100)
abc <- sample(letters[1:5], 1000, replace = T)
df <- data.frame(v1=abc, v2="blank", stringsAsFactors = F)
head(df)
system.time({
df$v2 <- ifelse(df$v1 == "a", "apple",
ifelse(df$v1 == "b", "ball",
ifelse(df$v1 == "c", "cat",
ifelse(df$v1 == "d", "dog", "elephant"))))
})
head(df)
# user system elapsed
# 0.001 0.000 0.001
# Same logic with switch()
set.seed(100)
abc <- sample(letters[1:5], 1000, replace = T)
df <- data.frame(v1=abc, v2="blank", stringsAsFactors = F)
system.time({
for(i in 1:nrow(df)){
val <- df$v1[i]
df$v2[i] <- switch(val,
"a"="apple",
"b"="banana",
"c"="cat",
"d"="dog",
"e"="elephant")
}
})
# user system elapsed
# 0.044 0.002 0.045
head(df)
@wolfganglederer

This comment has been minimized.

Copy link

wolfganglederer commented Nov 9, 2016

Some more methds and an even faster one

library(microbenchmark)
library(dplyr)

set.seed(100)
abc <- sample(letters[1:5], 1000, replace = T)
df <- data.frame(v1=abc, v2="blank", stringsAsFactors = F)
head(df)

v_ifelse <- function(df) {ifelse(df$v1 == "a", "apple",
ifelse(df$v1 == "b", "ball",
ifelse(df$v1 == "c", "cat",
ifelse(df$v1 == "d", "dog", "elephant"))))}

v_if_else <- function(df) {if_else(df$v1 == "a", "apple",
if_else(df$v1 == "b", "ball",
if_else(df$v1 == "c", "cat",
if_else(df$v1 == "d", "dog", "elephant"))))}

v_loop <- function(df) {for(i in 1:nrow(df)){
val <- df$v1[i]
df$v2[i] <- switch(val,
"a"="apple",
"b"="banana",
"c"="cat",
"d"="dog",
"e"="elephant")}}

v_apply <- function(df) df$v2 <- sapply(df$v1,function(val)switch(val,
"a"="apple",
"b"="banana",
"c"="cat",
"d"="dog",
"e"="elephant"), simplify = TRUE )

v_subset <- function(df){helper <- c(a = "apple", b = "banana", c = "cat", d = "dog", e = "elephant")
df$v2 <- helper[df$v1]}

microbenchmark(
v_if_else(df),
v_ifelse(df),
v_loop(df),
v_apply(df),
v_subset(df))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.