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

前端 未结 4 1173
一生所求
一生所求 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 08:54

    You could use case_when from the dplyr library:

    df1$y <- case_when(
        x == 1 ~ "s",
        x == 2 ~ "t",
        x == 3 ~ "u",
        x == 4 ~ "v",
        TRUE ~ "w"
    )
    

    Note that the final case above (TRUE) is the blanket else condition which will catch all cases not matching any earlier conditions.

提交回复
热议问题