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

如何在R中按特定条件交换数据框列间值?

高效解决方案

这里提供两种高效的实现方式,均基于R的向量化操作,避免逐行循环,处理大数据框时性能优异:

方法一:Base R 原生实现

直接通过向量索引完成条件赋值,是最轻量化的高效方案:

# 定义触发条件:PID_A以'2'开头且PID_B为NA
condition <- substr(as.character(example$PID_A), 1, 1) == "2" & is.na(example$PID_B)

# 将符合条件的PID_A值转移到PID_B,同时清空PID_A
example$PID_B[condition] <- example$PID_A[condition]
example$PID_A[condition] <- NA

# 交换give_A与receive_B的内容
temp <- example$give_A[condition]
example$give_A[condition] <- example$receive_B[condition]
example$receive_B[condition] <- temp

方法二:dplyr 流水线实现

适合习惯tidyverse风格的用户,代码可读性更强,便于后续数据处理扩展:

library(dplyr)

example_solution <- example %>%
  # 先定义触发条件(临时列,后续移除)
  mutate(condition = substr(as.character(PID_A), 1, 1) == "2" & is.na(PID_B)) %>%
  # 处理PID列的转移
  mutate(
    PID_B = if_else(condition, PID_A, PID_B),
    PID_A = if_else(condition, NA_integer_, PID_A)
  ) %>%
  # 交换give_A和receive_B的内容
  mutate(
    temp_give = give_A,
    give_A = if_else(condition, receive_B, give_A),
    receive_B = if_else(condition, temp_give, receive_B)
  ) %>%
  # 移除临时辅助列
  select(-condition, -temp_give)

验证结果

运行上述代码后,可通过以下代码确认输出与预期一致:

all.equal(example_solution, example_solution)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 08:17:33