首页 > 解决方案 > 使用行号在 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

标签: r

解决方案


不是使用which,而是as.integergrepl结果使用 - 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

推荐阅读