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

如何将数据框中OtherMainSource列内容替换至WaterSource对应位置?

解决R数据框中指定条件的列值替换问题

这里提供两种简洁的实现方式,都能满足你的需求:

方法1:基础R原生操作

直接通过逻辑索引定位需要替换的行,完成赋值:

# 筛选出WaterSource为指定值的行,替换为OtherMainSource对应内容
DF$WaterSource[DF$WaterSource == "Other (please specifiy)"] <- DF$OtherMainSource[DF$WaterSource == "Other (please specifiy)"]

方法2:tidyverse/dplyr风格实现

如果你习惯使用tidyverse生态,用dplyr的mutate+if_else更直观:

library(dplyr)

DF <- DF %>%
  mutate(WaterSource = if_else(
    condition = WaterSource == "Other (please specifiy)",
    true = OtherMainSource,
    false = WaterSource
  ))

运行任意一种方法后,你都会得到目标数据框:

> DF
   WaterSource OtherMainSource
1         Rain            <NA>
2  Piped Water            <NA>
3         Well            <NA>
4        River           River
5         Rain            <NA>
6 Water vendor    Water vendor

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 07:42:06