You need to enable JavaScript to run this app. R语言dplyr使用多条件case_when按分组为数据框新增列
优惠活动
大模型
产品
解决方案
定价
更多

R语言dplyr使用多条件case_when按分组为数据框新增列

你可以用dplyr包的分组操作和条件判断实现需求,代码如下:

首先加载依赖包:

library(dplyr)

数据处理代码:

# 注意修正原始数据里的笔误:0203是八进制字面量,实际应为0.203,可根据你的真实数据调整
df <- data.frame(Day=c(0,0,0,1,1,1),type=c("tr1","tr2","ctrl","tr1","tr2","ctrl"),
                mean=c(0.211,0.203,0.199,0.119,0.001,0.254), 
                sd=c(0.07,0.141,0.096, 0.0848, 0.0006, 0.0474))

df_result <- df %>%
  # 按Day字段分组
  group_by(Day) %>%
  mutate(
    # 提取当前分组内ctrl行的mean - sd作为判断阈值
    ctrl_threshold = mean[type == "ctrl"] - sd[type == "ctrl"],
    # 按条件给new.col赋值
    new.col = case_when(
      type == "ctrl" ~ NA_character_,
      (mean + sd) > ctrl_threshold ~ "yes",
      TRUE ~ "no"
    )
  ) %>%
  # 删除临时计算的阈值列,仅保留原有列+新增的new.col
  select(-ctrl_threshold)

执行后输出的df_result和你预期的结果完全匹配:

# A tibble: 6 × 5
# Groups:   Day [2]
    Day type   mean     sd new.col
  <dbl> <chr> <dbl>  <dbl> <chr>  
1     0 tr1   0.211 0.07   yes    
2     0 tr2   0.203 0.141  yes    
3     0 ctrl  0.199 0.096  NA     
4     1 tr1   0.119 0.0848 no     
5     1 tr2   0.001 0.0006 no     
6     1 ctrl  0.254 0.0474 NA  

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 10:06:02