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

满足条件时替换wide df指定列的值(R语言)

解决宽格式数据中指定列的替换问题

方法一:基础R实现

直接通过索引和循环完成需求:

# 获取change等于1的行索引
target_rows <- which(df$change == 1)

# 遍历目标行,替换对应列的值
for (row_idx in target_rows) {
  target_col <- df$change_date[row_idx]
  # 列名存在且不为NA时执行替换
  if (!is.na(target_col) && target_col %in% colnames(df)) {
    df[row_idx, target_col] <- "CHANGE"
  }
}

# 查看处理后的数据
df

方法二:tidyverse风格实现

如果使用dplyr,可以用按行处理的方式完成:

library(dplyr)

df <- df %>%
  rowwise() %>%
  mutate(
    # 动态引用change_date对应的列,替换目标值
    !!sym(change_date) := ifelse(change == 1, "CHANGE", !!sym(change_date))
  ) %>%
  ungroup()

# 查看结果
df

两种方法都能达成需求:将change == 1的行中,change_date指定的列值替换为"CHANGE"。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 09:14:55