简体   繁体   中英

Creating a new variable with levels in R

I am very much a novice to R and currently struggling to learn the language. What I am trying to do is create a new variable with three levels (if that makes sense). I am trying to show growth <=0%,<1%, and >=1% all in the same new variable (let me know if that is even possible).

So far I have tried this:

pincome$perctchng<- ifelse(pincome$perctchng<=0,ifelse(pincome$perctchng<1,
              ifelse(pincome$perctchng>=1,"level 1","level 2","level 3")))

This is the code that I attempted. I know that it is wrong, but any advice is the right direction is welcomed.

Thanks!

Nested ifelse statements are almost never the right answer. They're hard to read and fragile. Your goal is to transform a continuous value (the numeric values in perctchng ) into a categorical value ('level 1', etc). R's cut function is perfect for this:

pincome <- data.frame(perctchng = c(-2, -1, 0, 1, 2, 5))

  perctchng
1        -2
2        -1
3         0
4         1
5         2
6         5

pincome$level <- cut(pincome$perctchng, c(-Inf, 0, 1, Inf), c('level 1', 'level 2', 'level 3'))

  perctchng   level
1        -2 level 1
2        -1 level 1
3         0 level 1
4         1 level 2
5         2 level 3
6         5 level 3

Your solution is almost good your syntax is just not right :

library(dplyr)

pincome <- data.frame(perctchng = c(-2, -1, 0, 1, 2, 5))

pincome %>%
  mutate(perctchng_level = ifelse(perctchng <= 0, "level 1",
                            ifelse(perctchng < 1, "level 2",
                                   ifelse(perctchng >= 1, "level 3", NA))))

results :

  perctchng perctchng_level
1        -2         level 1
2        -1         level 1
3         0         level 1
4         1         level 3
5         2         level 3
6         5         level 3

A tidyverse solution:

pincome$perctchng<- ifelse(pincome$perctchng<=0,ifelse(pincome$perctchng<1, ifelse(pincome$perctchng>=1,"level 1","level 2","level 3")))

library(tidyverse)
pincome <- pincome %>%
           mutate(perctchng = case_when(perctchng <= 0 ~ "level 1",
                                        perctchng < 1 ~ "level 2",
                                        perctchng >= 1 ~ "level 3",
                                        TRUE ~ NA_character_)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM