首页 > 解决方案 > 以其他列中的间隔为条件创建新列

问题描述

我的数据是

   Age
1:  13
2:   4
3:  14
4:  52
5:  63
6:  25
7:  53

我想要一个变量来说明以下特征:如果 1-13 岁 -> e,如果 14-25 岁 -> b,如果 26-100 岁 -> d

期望的输出

   Age Characterization
1:  13                e
2:   4                e
3:  14                b
4:  52                d
5:  63                d
6:  25                b
7:  53                d

输入

structure(list(Age = c(13L, 4L, 14L, 52L, 63L, 25L, 53L)), row.names = c(NA, 
-7L), class = c("data.table", "data.frame"))

标签: rdataframe

解决方案


尝试findInterval如下

within(
  df,
  Characterization <- c("e", "b", "d")[1 + findInterval(Age, c(13, 25, 100), left.open = TRUE)]
)

这使

  Age Characterization
1  13                e
2   4                e
3  14                b
4  52                d
5  63                d
6  25                b
7  53                d

数据

> dput(df)
structure(list(Age = c(13L, 4L, 14L, 52L, 63L, 25L, 53L)), row.names = c(NA, 
-7L), class = "data.frame")

推荐阅读