【问题标题】:how to group a column by it's values into 3 groups according to a range of numbers [duplicate]如何根据数字范围将列按其值分组为3组[重复]
【发布时间】:2021-06-20 08:11:33
【问题描述】:

我学习了 R 的基础知识,并尝试根据多个范围对列进行分组。我的专栏是 BMI,我想对其中的值进行分组,例如体重过轻、健康、超重和肥胖。请问我可以知道怎么做吗?我的数据框是 weight_log。

【问题讨论】:

  • 欢迎您-到目前为止您尝试了什么?请阅读this post,了解如何在 R 上提出一个好的问题。特别是,请编辑您的问题以包含dput(data) 的输出和您想要的输出。谢谢。

标签: r


【解决方案1】:

有很多方法可以使用 R 实现您的目标,但是当您在 StackOverflow 上发布问题以帮助我们解决问题时,我们鼓励您展示自己解决问题的尝试。

这是一个使用tidyverse 函数的类似示例,可能会帮助您入门:

# Load libraries
library(tidyverse)

# Generate some fake data for the example
subjects <- data.frame(height = rnorm(100, 1.6, 0.2),
                       weight = rnorm(100, 75, 20))

# Calculate BMI and categorise subjects (per wikipedia)
subjects %>%
  mutate(BMI = weight / (height^2)) %>%
  mutate(`BMI category` = case_when(
    BMI < 15 ~ "Very severely underweight",
    BMI >= 15 & BMI < 16 ~ "Severely underweight",
    BMI >= 16 & BMI < 18.5 ~ "Underweight",
    BMI >= 18.5 & BMI < 25 ~ "Normal",
    BMI >= 25 & BMI < 30 ~ "Overweight",
    BMI >= 30 & BMI < 35 ~ "Moderately obese",
    BMI >= 35 & BMI < 40 ~ "Severely obese",
    BMI >= 40 ~ "Very severely obese")
  )
#      height    weight      BMI              BMI category
#1   1.600551  90.82957 35.45588            Severely obese
#2   1.673910  90.08658 32.15111          Moderately obese
#3   1.284048  47.01420 28.51456                Overweight
#4   1.474780 113.51028 52.18918       Very severely obese
#5   1.778946  90.02104 28.44581                Overweight
#6   1.353927  65.38778 35.67025            Severely obese
#7   1.492418  75.08285 33.71010          Moderately obese
#8   1.567819  51.66703 21.01947                    Normal
...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-04-27
    • 1970-01-01
    • 2017-07-13
    • 2023-04-08
    • 2022-12-04
    • 2013-01-27
    • 1970-01-01
    • 2018-06-25
    相关资源
    最近更新 更多