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

R语言统计dataframe每行非零列与零列数量的实现方法

方法1:使用dplyr(你尝试过的mutate方案)

先加载dplyr包,代码如下:

library(dplyr)

# 方案1:不提前修改数据类型,直接完成统计
df <- df %>%
  mutate(
    # 遍历所有列转数值后判断是否为0,按行求和得到零值列数量
    Zero = rowSums(across(everything(), ~as.numeric(.x) == 0)),
    # 非零列数量=总列数-零值列数量
    NonZero = ncol(df) - Zero
  )

# 方案2:先把所有数据列转成数值型,后续处理更便捷
df <- df %>%
  # 所有列批量转数值
  mutate(across(everything(), as.numeric)) %>%
  mutate(
    Zero = rowSums(. == 0),
    NonZero = ncol(.) - Zero
  )

方法2:无需加载第三方包的base R方案

# 先统计每行零值数量
zero_cnt <- rowSums(apply(df, 1, function(x) as.numeric(x) == 0))
# 给数据框赋值新列
df$Zero <- zero_cnt
df$NonZero <- length(df) - zero_cnt

运行上述任意一种方案,都可以得到你期望的输出结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 19:36:00