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

R语言按分组统计各变量首个1出现行号并批量新增列的实现问题

R 批量实现分组统计首个1出现行号的解决方案

你可以直接使用dplyr的across()语法批量处理所有目标列,无需重复编写逻辑,代码如下:

library(tidyverse)

# 原始数据集
test_df=data.frame(Group=c(1,1,1,1,2,2),var1=c(1,0,0,1,1,1),var2=c(0,0,1,1,0,0),var3=c(0,1,0,0,0,1))

# 批量计算out列
result_df <- test_df %>%
  group_by(Group) %>%
  mutate(
    # 可根据实际列名规则调整匹配逻辑,比如换为contains、ends_with等
    across(starts_with("var"), 
           # 计算逻辑:取第一个1的行号,无1则返回0
           function(x) {
             first_pos <- which(x == 1)[1]
             return(ifelse(is.na(first_pos), 0, first_pos))
           },
           # 新列命名规则
           .names = "out{sub('var', '', .col)}"
    )
  ) %>%
  ungroup()

运行后result_df就是完全符合预期的结果,适配任意数量的var列。

如果不想依赖tidyverse,也可以用基础R的ave()实现相同效果:

# 提取所有需要处理的var列名
var_cols <- grep("^var", names(test_df), value = T)
# 批量生成对应out列
test_df[, paste0("out", sub("var", "", var_cols))] <- lapply(var_cols, function(col) {
  ave(test_df[[col]], test_df$Group, FUN = function(x) {
    first_pos <- which(x == 1)[1]
    ifelse(is.na(first_pos), 0, first_pos)
  })
})

内容的提问来源于stack exchange,提问作者Ruser-lab9

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 16:18:02