尝试使用R中的多个if else语句创建新列 [英] Trying to create a new column using multiple if else statements in R

查看:76
本文介绍了尝试使用R中的多个if else语句创建新列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个新列,将一个人的BMI划分为某些类别.

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已经提到了 cut 函数.所以这是代码:

@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))

这篇关于尝试使用R中的多个if else语句创建新列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆