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

如何在R中多次重复执行指定函数,按循环时间点为数据框新增可变数量行

实现方法

你可以直接批量生成对应数量的待新增行后合并到原数据框,比循环调用新增行函数效率更高,调整后代码如下:

library(tidyverse)

timepoint <- c("Day 0", "Day 1", "Day 2")
for (i in timepoint) {
  # 计算当前时间点需要新增的行数
  cluster_participants <- length(unique(IgH_CDR3_cluster_count_combined$ID))
  total_participants <- nrow(unique(select(filter(IgH_CDR3_cluster, Time == i), ID)))
  repeats <- as.numeric(total_participants - cluster_participants)
  
  # 仅当需要新增行数大于0时执行操作
  if (repeats > 0) {
    # 批量生成repeats行新数据,cluster列可根据你的需求修改赋值规则
    new_rows <- data.frame(
      time = rep(i, repeats),
      count = rep(0, repeats),
      cluster = NA_character_
    )
    # 合并新行到原数据框
    df1 <- bind_rows(df1, new_rows)
  }
}

如果确实需要按你的要求重复执行add_row函数repeats次,可以用reduce实现:

library(tidyverse)

timepoint <- c("Day 0", "Day 1", "Day 2")
for (i in timepoint) {
  cluster_participants <- length(unique(IgH_CDR3_cluster_count_combined$ID))
  total_participants <- nrow(unique(select(filter(IgH_CDR3_cluster, Time == i), ID)))
  repeats <- as.numeric(total_participants - cluster_participants)
  
  if (repeats > 0) {
    df1 <- reduce(1:repeats, ~ .x %>% add_row(time = i, count = 0), .init = df1)
  }
}

注意事项

  • 你提供的df1结构中时间列名为小写time,你原有代码中筛选用的是大写Time,请统一列名避免筛选失效
  • 新增行的cluster列如果需要填充固定值/对应值,直接修改new_rows中cluster列的赋值规则即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 20:06:01