r - 使用行号在 R 中创建 0/1 列
问题描述
我想在我的数据集中创建一个新列,当“death_code”包含“I”(可能是 I001-I100)时,它将返回 1,否则将返回 0
death_code
I099
E045
T054
I065
I022
我使用 grepl 在包含“I”的变量中搜索行并保存了行号
rows<-which(grepl('I', fulldata$deathcode))
但是,我现在想在新列中为这些行分配 1,但我无法锻炼如何执行此操作。
这就是我预计数据的样子
death_code CVD_death
I099. 1
E045. 0
T054. 0
I065. 1
I022. 1
解决方案
不是使用which
,而是as.integer
对grepl
结果使用 - TRUE/FALSE 将转换为 1/0。
fulldata$CVD_death <- as.integer(grepl("I", fulldata$deathcode))
或者,您可以which
通过将列中的所有值设置为 0,然后将which
值设置为 1 来实现:
fulldata$CVD_death <- 0
fulldata$CVD_death[which(grepl("I", fulldata$deathcode))] <- 1
推荐阅读
- three.js - 将衬衫放在 3d 头像上的 API
- powerbi - 为什么我的父子路径功能不起作用(Power BI)?
- python - 如何使用 matplotlib 可视化多个特征
- java - 无法使用 Selenium 代码识别出发日期选择器(用于 makemytrip 网站)
- c# - C# 为包装数据列表实现 ICollection 接口
- swift - 我想通过滑动尾随更新表格视图中列出的数据
- mysql - 如何将复制的字体保存在mysql数据库中?
- javascript - 如何在跟踪代码管理器中获取图像文件名作为变量
- vue.js - Vue V-for 在选定的索引上
- angular - 如何使用 Angular UI 库 PrimeNG 在 tabMenu 标题中获得下拉菜单?