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

在R中根据数值条件交换dataframe两列值的实现方法

实现方法

首先定义原始数据框:

df <- structure(list(id = c(1, 2, 3), nd = c(NA, 20076, NA), dm = c(10113, NA, 10188)), class = "data.frame", row.names = c(NA, -3L))

方法一:Base R 实现

通过遍历行,根据条件交换列值:

for (i in 1:nrow(df)) {
  nd_val <- df$nd[i]
  dm_val <- df$dm[i]
  
  # dm列值小于20000时,移到nd列
  if (!is.na(dm_val) && dm_val < 20000) {
    df$nd[i] <- dm_val
    df$dm[i] <- NA
  }
  
  # nd列值大于20000时,移到dm列
  if (!is.na(nd_val) && nd_val > 20000) {
    df$dm[i] <- nd_val
    df$nd[i] <- NA
  }
}

方法二:Tidyverse (dplyr) 实现

利用dplyr的mutate和case_when进行向量化处理,代码更简洁:

library(dplyr)

df <- df %>%
  mutate(
    nd = case_when(
      !is.na(dm) && dm < 20000 ~ dm,
      !is.na(nd) && nd <= 20000 ~ nd,
      TRUE ~ NA_real_
    ),
    dm = case_when(
      !is.na(nd) && nd > 20000 ~ nd,
      !is.na(dm) && dm >= 20000 ~ dm,
      TRUE ~ NA_real_
    )
  )

执行上述任意一种方法后,均可得到目标数据框:

structure(list(id = c(1, 2, 3), nd = c(10113, NA, 10188), dm = c(NA, 20076, NA)), class = "data.frame", row.names = c(NA, -3L))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 09:31:00