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

在R中基于数据框多列多行生成样本最终结果列的问题

解决方案

方法一:Base R 实现

利用ave()函数按sample_ID分组判断,快速生成目标列:

# 先构造示例数据框(可替换为你的实际数据)
df <- data.frame(
  sample_ID = c("sample1", "sample1", "sample1", "sample2", "sample2", 
                "sample3", "sample3", "sample4", "sample4", "sample4"),
  date = c("1/1/2022", "1/1/2022", "1/1/2022", "2/1/2022", "3/1/2022", 
           "4/1/2022", "5/1/2022", "5/1/2022", "6/1/2022", "7/1/2022"),
  test_result = c("positive", "negative", "negative", "positive", "negative",
                  "negative", "positive", "negative", "negative", "negative")
)

# 添加final_result列
df$final_result <- ave(df$test_result, df$sample_ID, 
                       FUN = function(x) ifelse(any(x == "positive"), "positive", "negative"))

方法二:tidyverse(dplyr)实现

如果习惯管道式语法,用分组+突变的方式更直观:

library(dplyr)

df <- df %>%
  group_by(sample_ID) %>%
  mutate(final_result = ifelse(any(test_result == "positive"), "positive", "negative")) %>%
  ungroup()

两种方法都能达成需求:只要某样本存在任意一条positive结果,该样本所有行的final_result都为positive;全为negative则结果为negative。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 14:56:28