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

基于指定规则修改DataFrame中Days与Outcome列值的技术需求

解决方案:按规则修改DataFrame数据

原始数据

dfold <- structure(list(Person_id = c(50L, 234L, 555L), Days = c(94L, 102L, 50L), Outocme = c(1L, 1L, 0L)), class = "data.frame", row.names = c(NA, -3L))

修改规则

  • 若Days列数值超过100,将其改为100,同时对应Outocme列设为0
  • 若Outocme列值已为0,无论Days数值如何,将Days改为100

实现方法

方法1:Base R 写法

# 复制原始数据,避免修改原数据集
dfnew <- dfold

# 先处理Outocme为0的情况,强制将Days设为100
dfnew$Days[dfnew$Outocme == 0] <- 100

# 处理Days>100且Outocme为1的情况:修改Days为100,同时Outocme设为0
target_idx <- dfnew$Days > 100 & dfnew$Outocme == 1
dfnew$Days[target_idx] <- 100
dfnew$Outocme[target_idx] <- 0

方法2:dplyr 管道写法(适配tidyverse工作流)

library(dplyr)

dfnew <- dfold %>%
  mutate(
    # 优先处理Outocme=0的场景,Days直接设为100
    Days = ifelse(Outocme == 0, 100, Days),
    # 再处理Days>100的场景,将Days修正为100
    Days = ifelse(Days > 100, 100, Days),
    # 对刚被修正为100的Days行,同步把Outocme设为0
    Outocme = ifelse(Days == 100 & Outocme == 1, 0, Outocme)
  )

最终结果

运行上述代码后,得到的dfnew结构与预期一致:

> dput(dfnew)
structure(list(Person_id = c(50L, 234L, 555L), Days = c(94L, 100L, 100L), Outocme = c(1L, 0L, 0L)), class = "data.frame", row.names = c(NA, -3L))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 12:22:46