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

R语言:将阈值下新冠变异株数据合并至Other列的实现需求

解决方案代码
# 原始数据
df <- data.frame(
  Week_Count = seq(1,3),
  "Omicron BN.1" = c(0.05, 0.05, 0.10),
  "Omicron BA.5" = c(0.75, 0.50, 0.65),
  "Omicron CH.1" = c(0.10, 0.25, 0.10),
  Other = c(0.10, 0.20, 0.15)
)

# 1. 确定需要检查的变异株列(排除Week_Count和Other)
target_cols <- setdiff(names(df), c("Week_Count", "Other"))

# 2. 判断哪些列的所有观测值都≤0.1
cols_to_merge <- target_cols[sapply(df[target_cols], function(x) all(x <= 0.1))]

# 3. 将这些列的数值合并到Other列
df$Other <- df$Other + rowSums(df[cols_to_merge], na.rm = TRUE)

# 4. 保留需要的列:Week_Count、未被合并的变异株列、更新后的Other列
cols_to_keep <- c("Week_Count", setdiff(target_cols, cols_to_merge), "Other")
df_final <- df[cols_to_keep]

# 查看结果
df_final
代码解释
  • 步骤1:用setdiff排除不需要检查的Week_Count和Other列,得到所有需要判断的变异株列名。
  • 步骤2:用sapply遍历每个变异株列,通过all(x <= 0.1)判断该列所有值是否都≤0.1,筛选出需要合并到Other的列。
  • 步骤3:用rowSums计算每一行中需要合并的列的总和,加到原Other列上,完成数值合并。
  • 步骤4:整理需要保留的列(原Week_Count、未被合并的变异株列、更新后的Other),生成最终数据框。

运行代码后得到的结果和期望完全一致:

> df_final
  Week_Count Omicron.BA.5 Omicron.CH.1 Other
1          1         0.75         0.10  0.15
2          2         0.50         0.25  0.25
3          3         0.65         0.10  0.25

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 15:18:32