How to simplify handling with nested ifelse() structures in base R?

前端 未结 4 1121
一生所求
一生所求 2021-01-21 08:49

I\'m facing nested ifelse() structures:

df1$var <- ifelse(x < a, u, ifelse(x < b, v, ifelse(x < c, w, ...)))

whereby t

4条回答
  •  感情败类
    2021-01-21 09:16

    In base R, if there are multiple elements to be replaced, create a key/value dataset and do a merge

    keyval <- data.frame(x = c(1, 2, 3, 4), y = c("s", "t", "u", "v"), stringsAsFactors = FALSE)
    new <- merge(df1, keyval, by = 'x', all.x = TRUE)[['y']]
    new[is.na(new)] <- "w"
    df1$x <- new
    

    data

    set.seed(24)
    df1 <- data.frame(x = rbinom(100, 5, .5))
    

提交回复
热议问题