r - 以其他列中的间隔为条件创建新列
问题描述
我的数据是
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"))
解决方案
尝试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")
推荐阅读
- imagemagick - magickimage montage *.png -colorspace CMYK test.png 结果图片改变了色彩空间?我不明白如何解决它?
- ruby-on-rails - 将设计添加到现有应用程序 - 未定义的方法 `sign_in' for #
- android - Android - 有没有办法使用 recyclerview.addOnScrollListener 作为函数
- python - python如何获取不属于模板的所有图像
- excel - 将公式转换为字符串 vba
- javascript - 在 Google Apps 脚本中为项目列表分配一个数字(最多 50 个)
- python - 索引非常大的 Pandas 数据帧的最快方法
- c++ - 如果在编译时大小未知,如何在堆栈上分配数组?
- javascript - 为什么这个函数返回相同的 id?
- go - 在 GOLang 中导入下载的包时出现恐慌