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

如何在R大数据集中统计每行≥1的列数(蛋白拷贝数场景)

解决方案

基础R方法

直接使用rowSums()函数,将数据框中每个元素与1比较生成逻辑矩阵,再对每行求和(逻辑值TRUE会被当作1,FALSE当作0),这是最高效的方式,尤其适合大规模数据集:

# 加载示例数据
df <- structure(list(Atrsp2 = c(0, 2, 0, 0, 0, 0, 0, 0, 0), Bifad1 = c(0, 
0, 0, 0, 0, 0, 0, 0, 0), Rhoto1 = c(0, 2, 0, 0, 0, 0, 0, 0, 0
), Ascsa1 = c(0, 1, 0, 0, 0, 0, 0, 0, 0), Pirin1 = c(0, 1, 0, 
0, 0, 0, 0, 0, 0), Phisc1 = c(0, 1, 0, 0, 0, 0, 0, 0, 0), Xylhe1 = c(0, 
1, 0, 0, 0, 0, 0, 0, 0), Geopyr1 = c(0, 0, 0, 0, 0, 0, 0, 0, 
0), Mucend1 = c(0, 2, 0, 0, 0, 0, 0, 2, 0)), row.names = c("100596", 
"103485", "104973", "112416", "116745", "125161", "12870", "15275", 
"189813"), class = "data.frame")

# 新增统计列
df$species_count <- rowSums(df >= 1)

运行后查看结果:

df
#>          Atrsp2 Bifad1 Rhoto1 Ascsa1 Pirin1 Phisc1 Xylhe1 Geopyr1 Mucend1 species_count
#> 100596       0      0      0      0      0      0      0       0       0              0
#> 103485       2      0      2      1      1      1      1       0       2              7
#> 104973       0      0      0      0      0      0      0       0       0              0
#> 112416       0      0      0      0      0      0      0       0       0              0
#> 116745       0      0      0      0      0      0      0       0       0              0
#> 125161       0      0      0      0      0      0      0       0       0              0
#> 12870        0      0      0      0      0      0      0       0       0              0
#> 15275        0      0      0      0      0      0      0       0       2              1
#> 189813       0      0      0      0      0      0      0       0       0              0

tidyverse方法

如果你习惯使用dplyr,可以结合rowSums()和across()实现,同样高效:

library(dplyr)

df <- df %>%
  mutate(species_count = rowSums(across(everything(), ~ .x >= 1)))

为什么这个方法高效?

rowSums()是向量化运算,底层用C实现,比循环、apply()或嵌套ifelse快得多,完全能应对数千行×数千列的大规模数据集。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 17:23:16