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

如何将R数据框中1之后的连续数值置为0?

解决R数据框中每列首次出现1后所有值置0的问题

基础R实现

首先构造你的数据框:

df <- data.frame(a = c(0,0,0,0,1,1,1,0,0,0),
                 b = c(0,0,1,1,1,1,0,0,0,0),
                 c = c(1,1,0,0,0,0,0,1,1,0))

定义处理单列的函数,找到第一个1的位置后,将其后续所有值置为0:

process_col <- function(col) {
  first_one <- which(col == 1)[1]
  if (!is.na(first_one)) {
    col[(first_one + 1):length(col)] <- 0
  }
  col
}

# 应用到所有列并转换回数据框
df_processed <- as.data.frame(apply(df, 2, process_col))

查看处理结果:

print(df_processed)
#>    a b c
#> 1  0 0 1
#> 2  0 0 0
#> 3  0 0 0
#> 4  0 0 0
#> 5  1 0 0
#> 6  0 0 0
#> 7  0 0 0
#> 8  0 0 0
#> 9  0 0 0
#> 10 0 0 0

dplyr风格实现

如果你习惯使用tidyverse工具,可以用dplyr::across()实现:

library(dplyr)

df_processed <- df %>%
  mutate(across(everything(), ~{
    first_one <- which(.x == 1)[1]
    if (!is.na(first_one)) {
      .x[(first_one + 1):length(.x)] <- 0
    }
    .x
  }))

两种方法都能实现需求:保留每列第一个出现的1,将其之后的所有数值(包括后续的1)置为0;如果列中没有1,则保持原数据不变。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 21:11:39