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

如何在R中基于已有数据框创建含重复值与计算结果的新数据框?

解决方案

首先先构造你的原始数据框:

df <- data.frame(
  Dose = c(0.2, 0.3, 0.4),
  Num.Infected = c(1, 2, 3),
  Num.Uninfected = c(5, 4, 3)
)

方法一:使用tidyverse工具(推荐)

用dplyr和tidyr的组合可以简洁实现需求,不需要手动写复杂循环:

library(tidyverse)

new_df <- df %>%
  rowwise() %>%  # 按行处理每一条记录
  mutate(Score = list(c(rep(1, Num.Infected), rep(0, Num.Uninfected)))) %>%  # 生成对应数量的1和0并存为列表
  unnest(Score) %>%  # 将列表展开为多行
  select(Dose, Score)  # 保留需要的两列

方法二:Base R循环实现

如果你习惯用基础R的循环写法,这样修改就能达到目的:

# 初始化空数据框
new_df <- data.frame(Dose = numeric(), Score = integer())

# 遍历原始数据的每一行
for (i in 1:nrow(df)) {
  current_dose <- df$Dose[i]
  # 生成感染者对应的行
  infected_rows <- data.frame(Dose = rep(current_dose, df$Num.Infected[i]), Score = 1)
  # 生成未感染者对应的行
  uninfected_rows <- data.frame(Dose = rep(current_dose, df$Num.Uninfected[i]), Score = 0)
  # 把两行数据合并到新数据框中
  new_df <- rbind(new_df, infected_rows, uninfected_rows)
}

运行任意一种方法后,new_df就是你需要的格式。

内容的提问来源于stack exchange,提问作者K.W

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 23:03:21