以其他列中的间隔为条件创建新列

时间:2020-10-15 11:45:02

标签: r dataframe

我的数据是

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

1 个答案:

答案 0 :(得分:0)

像下面一样尝试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")