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

R语言如何基于col列重复值更新author列空值且保留value值

实现方案

核心逻辑是按col列分组,取每组内唯一的非空author值,填充该组所有行的author字段,全程不修改value系列列的原有值。下面给出两种常用实现方式:


方案1:tidyverse(dplyr)实现

# 加载依赖
library(dplyr)

# 构造示例数据
df <- data.frame(
  col = c("Acer laurinum", "Acer laurinum", "Acronychia pedunculata", "Acronychia pedunculata"),
  author = c("", "Hassk.", "(L.) Miq.", ""),
  value1 = c(1, 1, 0, 0),
  value2 = c(2, 3, 1, 0)
)

# 执行填充
df_result <- df %>%
  group_by(col) %>%
  mutate(author = author[author != ""][1]) %>%
  ungroup()

# 查看结果
df_result

方案2:base R 实现

无需额外安装依赖,直接用内置函数实现:

# 沿用上面构造的示例df
df$author <- ave(df$author, df$col, FUN = function(x) x[x != ""][1])

# 查看结果
df

两种方案输出结果完全匹配预期格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 04:15:05