You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用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]

最终结果

执行任意方法后,数据框将得到目标结果:

InvestedProgramParticipantInvested&Participated
100
00NA
111
100
01NA
00NA

内容的提问来源于stack exchange,提问作者TvCasteren

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 08:05:26