使用Ifelse或DPLYR case_when生成新虚拟列遇NA赋值问题
解决方案:生成条件赋值的新列
原始数据
可通过以下R代码复现你的数据框:
df <- data.frame( Invested = c(1, 0, 1, 1, 0, 0), ProgramParticipant = c(0, 0, 1, 0, 1, 0) )
需求说明
新增列Invested&Participated,规则:
- 当
Invested为1时,取值与ProgramParticipant一致(1或0) - 当
Invested为0时,赋值为NA
可行方法
方法1:基础R的ifelse函数
直接通过条件判断赋值,注意列名含特殊字符&,需用反引号包裹:
df$`Invested&Participated` <- ifelse(df$Invested == 1, df$ProgramParticipant, NA)
方法2:dplyr的case_when函数
需指定NA的类型(匹配ProgramParticipant的数值类型),避免类型不匹配问题:
library(dplyr) df <- df %>% mutate(`Invested&Participated` = case_when( Invested == 1 ~ ProgramParticipant, TRUE ~ NA_real_ # 若ProgramParticipant为整数型,可改用NA_integer_ ))
方法3:向量索引直接赋值
先初始化新列为NA,再给符合条件的行批量赋值:
df$`Invested&Participated` <- NA df$`Invested&Participated`[df$Invested == 1] <- df$ProgramParticipant[df$Invested == 1]
最终结果
执行任意方法后,数据框将得到目标结果:
| Invested | ProgramParticipant | Invested&Participated |
|---|---|---|
| 1 | 0 | 0 |
| 0 | 0 | NA |
| 1 | 1 | 1 |
| 1 | 0 | 0 |
| 0 | 1 | NA |
| 0 | 0 | NA |
内容的提问来源于stack exchange,提问作者TvCasteren
相关产品推荐
相关产品推荐

