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

R语言数据框筛选问题:提取符合条件的Orthogroups行

解决方案

基础R实现

先明确生物列的范围(第2到第48列),按你的需求分两步筛选:

# 定义生物列的索引
bio_cols <- 2:48

# 第一步:筛选所有生物列值均为0或1的行
filtered_all <- Orthogroups.GeneCount[rowSums(Orthogroups.GeneCount[bio_cols] %in% c(0, 1)) == length(bio_cols), ]

# 若第一步无结果,则执行第二步筛选
if (nrow(filtered_all) == 0) {
  result_df <- Orthogroups.GeneCount[rowSums(Orthogroups.GeneCount[bio_cols] %in% c(0, 1)) >= 32, ]
} else {
  result_df <- filtered_all
}

dplyr实现(解决你%>%无法使用的问题)

先确保加载dplyr包,再按逻辑处理:

library(dplyr)

bio_cols <- 2:48

# 先尝试筛选所有生物列符合条件的行
result_df <- Orthogroups.GeneCount %>%
  # 计算每行符合0/1条件的生物列数量
  mutate(valid_bio = rowSums(across(all_of(bio_cols), ~ .x %in% c(0, 1)))) %>%
  filter(valid_bio == length(bio_cols))

# 若结果为空,重新筛选至少32个符合条件的行
if (nrow(result_df) == 0) {
  result_df <- Orthogroups.GeneCount %>%
    mutate(valid_bio = rowSums(across(all_of(bio_cols), ~ .x %in% c(0, 1)))) %>%
    filter(valid_bio >= 32)
}

你之前尝试的问题说明

  • subset(Orthogroups.GeneCount, Orthogroups.GeneCount[1:48,] == 1) 错误在于:把整个数据框(含第一列字符型的Orthogroups)和1做比较,逻辑判断完全偏离需求,且subset的条件应为行级判断。
  • %>%无法工作大概率是因为没先运行library(dplyr)加载包,或是语法格式有误。

内容的提问来源于stack exchange,提问作者Carlos Alberto Lara Rojas

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 11:35:28