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

如何对dataframe应用列向逻辑?新增列存储每行首个值为0的列名

逐行定位首个0值对应列名的实现

通过dplyr的逐行处理逻辑配合mutate即可完成需求,无需编写额外循环:先对每一行提取所有列的取值,定位第一个值为0的位置,映射为对应列名,无匹配则返回NA。

代码实现

# 加载依赖包
library(dplyr)

# 原始示例数据
df <- data.frame(pred2014 = c(0,0,1), pred2015 = c(0,0,1),
                 pred2016 = c(0,1,1), measured2017 = c(0,0,1))

# 新增目标列
df_result <- df %>%
  rowwise() %>%
  mutate(
    first_zero_col = {
      # 获取当前行的全部列值
      row_vals <- c_across(everything())
      # 定位首个0值的索引
      zero_pos <- which(row_vals == 0)[1]
      # 映射列名,无匹配返回NA
      case_when(
        !is.na(zero_pos) ~ names(row_vals)[zero_pos],
        .default = NA_character_
      )
    }
  ) %>%
  ungroup()

输出结果

df_result
# A tibble: 3 × 5
#   pred2014 pred2015 pred2016 measured2017 first_zero_col
#      <dbl>    <dbl>    <dbl>        <dbl> <chr>         
# 1        0        0        0            0 pred2014      
# 2        0        0        1            0 pred2014      
# 3        1        1        1            1 NA  

可根据实际需求灵活调整逻辑:

  • 仅匹配指定前缀的列(比如只匹配pred开头的预测列),可将c_across(everything())替换为c_across(starts_with("pred"))
  • 需定位最后一个0值的列,可将取索引的代码改为zero_pos <- which(row_vals == 0) %>% last()
  • 需匹配1值的列,只需将row_vals == 0替换为row_vals == 1即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.25 06:36:03