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

如何使用函数与across()在tibble中生成条件列验证Total正确性

高效实现方法

直接用dplyr的across()结合rowSums()就能搞定,不用手动逐个列相加,代码如下:

library(dplyr)

# 生成condition列
animal_outcomes <- animal_outcomes %>%
  mutate(
    condition = as.integer(rowSums(across(ACT:WA), na.rm = TRUE) == Total)
  )

代码解释:

  • across(ACT:WA):精准选中从ACT到WA的所有目标列,列名连续时用这种范围写法最省心
  • rowSums(..., na.rm = TRUE):对每一行的目标列求和,na.rm = TRUE用来处理数据中可能存在的缺失值(无缺失可省略)
  • == Total:将每行的求和结果与Total列做等值判断,返回布尔值(TRUE/FALSE)
  • as.integer():把布尔值转换为1/0(TRUE对应1,FALSE对应0)

非连续列的处理方式

如果目标列不是连续排列的,可借助列选择器灵活选中:

# 示例:选中所有包含"state"关键词的列
animal_outcomes <- animal_outcomes %>%
  mutate(
    condition = as.integer(rowSums(across(contains("state")), na.rm = TRUE) == Total)
  )

内容的提问来源于stack exchange,提问作者a.sa.5969

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 03:27:11