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

R语言dplyr跨bias后缀列统计dog出现数及批量生成指示列

问题1:计算dog_sum且规避整行NA报错

原代码使用rowwise()的实现性能较低,且对全NA行的边界处理不好,改用rowSums()的向量化操作即可解决,代码如下:

library(dplyr)
test_df <- test_df %>%
  mutate(dog_sum = rowSums(across(ends_with("bias")) == "dog", na.rm = TRUE))

该方案无需逐行遍历,处理大表时性能远好于rowwise(),全NA行的计算结果会自动返回0,不会抛出错误。

问题2:生成各bias列对应的01标识列

直接利用mutate()+across()的.names参数自定义新列名即可实现需求:

test_df <- test_df %>%
  mutate(across(ends_with("bias"), ~ as.integer(.x %in% "dog"), .names = "{.col}_dog"))

这里使用%in%代替==是为了自动将NA值的判断结果转为FALSE,最终对应输出0,符合需求。

合并实现(两个需求一次性完成)

如果要同时完成两个计算,可合并为一段代码:

test_df <- test_df %>%
  mutate(
    # 生成各列的dog标识
    across(ends_with("bias"), ~ as.integer(.x %in% "dog"), .names = "{.col}_dog"),
    # 计算每行dog总数
    dog_sum = rowSums(across(ends_with("_dog")), na.rm = TRUE)
  )

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 06:57:04