简体   繁体   English

使用 R,如何根据范围内的数字为新列分配值?

[英]With R, how do i assign values to a new column based on numbers that fall within a range?

i have a column called reported age that can range from 0 to 100.我有一个名为报告年龄的列,范围从 0 到 100。

Report age|
         5
        82
        17
        39
        67

I would like to create a script that assigns a new column called Age Group我想创建一个脚本来分配一个名为 Age Group 的新列

Report age|Age Group|
         5    5 to 9
        82  80 to 84
        17  15 to 19
        39  35 to 39 
        67  64 to 69

I know if i have我知道我是否有

df <-df %>%
    mutate(Age_Group = ifelse(`Report age` <5, "Under 5", No)

I will get two outcomes.我会得到两个结果。 I want to set up way more.我想设置更多。 Under 5, 5 to 9, 10 to 14, 15 to 19, and so on until "85 years and over". 5 岁以下、5 岁至 9 岁、10 岁至 14 岁、15 岁至 19 岁,以此类推,直到“85 岁及以上”。

We can use cut to create the group我们可以使用cut创建组

library(dplyr)
brks <- c(5, 9, 15, 35, 39, 64, 69, 80, 84)

df %>%
   mutate(Age_Group = cut(`Report age`, 
      breaks = c(-Inf, brks, Inf),
      labels = c("under 5", paste(head(brks, -1),
                " to ", tail(brks, -1)), "85 years and over")))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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