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

R语言按分组将test行的type值赋值给组内所有行的实现方法

解法1:使用dplyr(tidyverse生态,最常用易读)

分组后直接匹配组内value为test对应的type值,填充到全组即可,代码如下:

library(dplyr)
df <- df %>%
  # 按指定字段分组
  group_by(participant, group) %>%
  # 提取组内value为test的type值,[1]适配单组有多个test的场景,默认取第一个匹配值
  mutate(test_type = type[value == "test"][1]) %>%
  ungroup()
解法2:Base R实现(无需安装第三方包)

用分组统计函数ave即可实现相同逻辑:

df$test_type <- with(df, ave(seq(nrow(df)), participant, group, FUN = function(idx) {
  type[idx[value[idx] == "test"]][1]
}))
解法3:data.table实现(大数据量下性能最优)
library(data.table)
# 转换为data.table格式
setDT(df)
# 分组赋值
df[, test_type := type[value == "test"][1], by = .(participant, group)]

以上三种方法均可以输出你给出的预期结果,如果你对应的业务场景中存在单组有多个value = "test"的记录,调整代码中的[1]为对应的取值逻辑(如取最后一个、取最大值等)即可适配。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 14:27:03