I\'m facing nested ifelse() structures:
df1$var <- ifelse(x < a, u, ifelse(x < b, v, ifelse(x < c, w, ...)))
whereby t
Since you insist on base R, here are two possibilities:
Define a mapping data.frame:
# Define mapping
map <- cbind.data.frame(
x = c(1, 2, 3, 4, NA),
y = c("s", "t", "u", "v", "w"));
Method 1: match entries from map to df1.
# match entries
df1$y <- map[match(df1$x, map$x), 2];
df1$y[is.na(df1$y2)] <- "w";
Method 2: Loop through all mappings, and replace using direct indexing:
# for loop
df1$y <- factor("w", levels = map$y);
for (i in 1:nrow(map)) df1$y[df1$x == map$x[i]] <- map$y[i];
Output:
tail(df1);
# x y
#95 4 v
#96 1 s
#97 4 v
#98 2 t
#99 4 v
#100 1 s
Note, the second method will also work for inequalities.
set.seed(2017);
df1 <- data.frame(x = rbinom(100, 5, .5))