You need to enable JavaScript to run this app. R语言中按双条件实现同一数据框内两列的合并操作
优惠活动
大模型
产品
解决方案
定价
更多

R语言中按双条件实现同一数据框内两列的合并操作

R 实现同一数据框内两列的条件式赋值

这里的需求本质不是拼接两列内容,而是满足双条件时的定向赋值:仅当salary为空且comp包含英镑符号£时,把对应行的comp内容填充到salary列,comp列本身保持不变,因此不需要用到paste()或跨表合并的函数。

基础R实现方法(无需依赖额外包)

  • 核心判断逻辑:
    • is.na(df$salary):筛选出salary无有效内容的行
    • grepl("£", df$comp, fixed = TRUE):筛选出comp包含£的行,fixed=TRUE表示直接匹配字符,无需按正则解析,运行效率更高
  • 完整代码:
# 载入示例数据
df <- structure(list(salary = c("£9.18 per hour", "£35,000 to £50,000 per year", 
"£29,000 to £30,000 per year", "£20,000 to £35,000 per year", 
"£29,000 to £31,000 per year", "£65 to £80 per day", "£65 to £75 per day", 
NA, NA, NA, NA, NA, NA), comp = c(NA, "Self employed, Commission Only", 
NA, NA, NA, NA, "Opportunity to become a permanent role.", NA, 
"£18,000 + Bonus & Benefits", "NMW + Overtime and Bonus", "Depending on experience", 
"£21,892 - £24,157 pa", "£38,890 -£44,503 per annum"), row.names = 19:31, class = "data.frame")

# 执行条件赋值
df$salary[is.na(df$salary) & grepl("£", df$comp, fixed = TRUE)] <- df$comp[is.na(df$salary) & grepl("£", df$comp, fixed = TRUE)]

dplyr实现方法(适合管道式数据处理场景)

如果日常用dplyr做数据清洗,可配合stringr的字符匹配函数实现,逻辑更直观易读:

library(dplyr)
library(stringr)

df <- df %>%
  mutate(
    salary = if_else(
      # 两个条件同时满足才执行替换
      is.na(salary) & str_detect(comp, fixed("£")),
      comp, # 满足条件则用comp的值填充salary
      salary # 不满足则保留salary原有内容
    )
  )

结果验证

运行上述任意一段代码后,输出结果和期望效果完全一致:

salary                                    comp
19              £9.18 per hour                                    <NA>
20 £35,000 to £50,000 per year          Self employed, Commission Only
21 £29,000 to £30,000 per year                                    <NA>
22 £20,000 to £35,000 per year                                    <NA>
23 £29,000 to £31,000 per year                                    <NA>
24          £65 to £80 per day                                    <NA>
25          £65 to £75 per day Opportunity to become a permanent role.
26                        <NA>                                    <NA>
27  £18,000 + Bonus & Benefits              £18,000 + Bonus & Benefits
28                        <NA>                NMW + Overtime and Bonus
29                        <NA>                 Depending on experience
30        £21,892 - £24,157 pa                    £21,892 - £24,157 pa
31  £38,890 -£44,503 per annum              £38,890 -£44,503 per annum

注意:如果你的数据中salary的空值不是NA而是空字符串"",只需把判断条件里的is.na(salary)替换为salary == ""即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.02 09:06:05