简体   繁体   中英

Trying to create a new column using multiple if else statements in R

I would like to create a new column that classifies a person's BMI into certain categories.

I am not sure where I am going wrong:

brfss2013 <- brfss2013 %>%
  mutate(bmi_class = if (X_bmi5 < 18.5) {
    X_bmi5 == 'underweight'}
    else if (X_bmi5 in range(18.5,24.9)){
      X_bmi5 =='normal'} 
    else if (X_bmi5 in range(25,29.9)) {
      X_bmi5 =='overweight'}
    else if (X_bmi5 in range(30,34.9)){
      X_bmi5 =='class 1 obesity'}
    else if (X_bmi5 in range(35,39.9)){
      X_bmi5 =='class 2 obesity'
    else if (X_bmi5 > 39.9){
      X_bmi5 == 'class 3 obesity')}
      else 'NA')

@joran already mentioned cut function. So here is the code:

# Fake data
brfss2013 <- data.frame(X_bmi5 = rnorm(30, 28, 5))

labels <- c('underweight', 'normal', 'overweight',
            'class 1 obesity', 'class 2 obesity', 'class 3 obesity')
breaks <- c(0, 18.5, 24.9, 29.9, 34.9, 39.9, 1000)
brfss2013 <- brfss2013 %>%
             mutate(brfss2013 = cut(X_bmi5, breaks = breaks,
                    labels = labels, include.lowest = TRUE))

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