Very useful function. Your best friend, whenever in need to recode anything. Requires three simple input data:
1) the condition to be verified,
2) operation to be performed when the condition is met (TRUE)
3) and operation to be performed when the condition is not met (FALSE)
It is really that simple as it sounds!
Create a simple, two-variable data frame:
set.seed(111) # for reproducible results
df <- data.frame(x = rnorm(100),
y = rbinom(n = 20, size = 100, prob = 0.5))
Now, let’s say you want to have a third, “z” variable, which is a two-level character variable (levels: “positive_50”, “other”), conditional on the other two variables: x > 0 and y >= 50.
Easy-peasy with ifelse().
df$z <- ifelse(df$x > 0 & df$y >= 50, # your condition
"positive_50", # value assigned to z when the condition is met
"other") # value assigned to z when the condition is not met
tail(df,10) # to explore the last 10 rows
## x y z
## 91 2.05074953 45 other
## 92 0.49080818 54 positive_50
## 93 -1.73147942 45 other
## 94 0.71088366 44 other
## 95 0.01382291 54 positive_50
## 96 -1.40104160 49 other
## 97 1.25912367 48 other
## 98 -0.12747752 63 other
## 99 -0.72938651 52 other
## 100 -1.21136136 48 other
Obviously, you can have any condition/conditional operation within ifelse() you can imagine.. Well… almost any… there are some limits;) …which does not really change the fact that R is great!