如果第一列有 1 并且其余列都为零,则计算该行

Count the row if the first column has 1 and the rest columns are all zero

我尝试结合使用 mutateifelse 在 R 中使用 dplyr 函数,但它不起作用。

enter image description here

第一列是订阅者 ID,其他列是剧集播出日期(按顺序)。 1 表示订阅者观看了该剧集,0 订阅者没有观看该剧集。

您可以像这样在 dplyr::mutate() 中使用辅助函数 dplyr::if_all()

library(dplyr)

# A simpler version of the dataset to illustrate
data <- tibble(
  "2021-07-07" = sample(c(1, 0), 1000, replace = TRUE),
  "2021-07-08" = sample(c(1, 0), 1000, replace = TRUE),
  "2021-07-09" = sample(c(1, 0), 1000, replace = TRUE),
)


data %>% 
  mutate(
    only_first = `2021-07-07` == 1 & if_all(-`2021-07-07`, ~ .x == 0)
  )

输出:

# A tibble: 1,000 x 4
   `2021-07-07` `2021-07-08` `2021-07-09` only_first
          <dbl>        <dbl>        <dbl> <lgl>     
 1            0            1            1 FALSE     
 2            0            0            0 FALSE     
 3            0            1            0 FALSE     
 4            1            1            1 FALSE     
 5            1            0            1 FALSE     
 6            0            1            1 FALSE     
 7            1            1            0 FALSE     
 8            1            0            1 FALSE     
 9            1            1            0 FALSE     
10            1            0            0 TRUE      
# ... with 990 more rows

逻辑分解

  • 2021-07-07 == 1 匹配第一列等于 1
  • 的行
  • if_all(-2021-07-07, ~ .x == 0) 匹配 所有 除了 第一个等于 0.
  • 的行
  • 如果上面描述的两个语句都是 TRUE& 给你 TRUE,如果不是 FALSE