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

R语言合并两列:双非NA值拼接,含NA则取非NA值

方法1:使用tidyverse工具(dplyr + stringr)

coalesce的作用是取首个非NA值,确实满足不了拼接需求。你可以用replace_na把NA转成空字符串,再用str_c完成拼接:

library(dplyr)
library(stringr)

df <- df %>%
  mutate(z = str_c(replace_na(x, ""), replace_na(y, "")))

方法2:Base R 原生实现

如果不想加载额外包,有两种原生写法可选:

方式A:替换NA为空字符串后拼接

df$z <- paste0(replace(df$x, is.na(df$x), ""), replace(df$y, is.na(df$y), ""))

方式B:逐情况判断拼接

df$z <- ifelse(is.na(df$x), 
               df$y, 
               ifelse(is.na(df$y), 
                      df$x, 
                      paste0(df$x, df$y)))

结果验证

运行上述任意代码后,生成的z列都会符合预期:

> df
     x    y  z
1    a    l al
2 <NA>    m  m
3    c <NA>  c
4    d    o do

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 16:10:33