R - 跨列的行数使用基于另一列中的值的特定起始列

R - row count across columns using specific starting column based on value in another column

卡在这个问题上有一段时间了。

对于每一行,我都尝试跨列计算所有大于 0 的值。但需要注意的是,我需要指定起始列以使用另一列中每一行的特定值开始计算。

例如 table 看起来像这样:

ID      |     StartWeek     |     1     |     2     |     3     |
123             2                 3           0           1
456             1                 1           0           1

预期输出如下所示:

ID      |     StartWeek     |     1     |     2     |     3     |   CountRow   |
123             2                 3           0           1           1
456             1                 1           0           1           2

我试过这样的事情:

df <- df %>%
mutate(CountRow = rowSums(.[StartWeek:5] > 0))

但它只是给我整列而不是每一行的单独值。我想我阅读了一个使用 groupby() 的潜在解决方案,但是通过访问每一行的特定值而不是调用整个列,可以通过另一种方式来做到这一点。

一种方法是将dataframe转为长格式,然后根据StartWeek过滤掉不需要的单元格,再进行计数。

library(tidyverse)
df <- tribble(
  ~ID, ~StartWeek, ~"1", ~"2", ~"3",
  123L, 2L, 3L, 0L, 1L,
  456L, 1L, 1L, 0L, 1L
)
df %>% pivot_longer(cols=-c(ID, StartWeek)) %>%
  mutate(name=as.integer(name)) %>% filter(name>=StartWeek, value>0) %>%
  group_by(ID) %>% summarize(CountRow=n(), .groups="drop") %>%
  left_join(df, ., by="ID")
#> # A tibble: 2 x 6
#>      ID StartWeek   `1`   `2`   `3` CountRow
#>   <int>     <int> <int> <int> <int>    <int>
#> 1   123         2     3     0     1        1
#> 2   456         1     1     0     1        2

reprex package (v1.0.0)

于 2021 年 3 月 11 日创建

对于每一行,我们可以计算 StartWeek 之后有多少个值大于 0。在 dplyr 中,我们可以使用 rowwise :

library(dplyr)

df %>%
  rowwise() %>%
  mutate(CountRow = { tmp <- c_across(`1`:`3`);
                      sum(tmp[StartWeek:length(tmp)] > 0)
                    })

#   ID    StartWeek   `1`   `2`   `3` CountRow
#  <int>     <int> <int> <int> <int>    <int>
#1   123         2     3     0     1        1
#2   456         1     1     0     1        2