我试图确定列中的哪些组包含特定序列长度的非零数字。在下面的基本示例中,目标是找到 a 序列长度为 5 的组,只有组 b
才是正确的。
set.seed(123)
df <- data.frame(
id = seq(1:40),
grp = sort(rep(letters[1:4], 10)),
x = c(
c(0, sample(1:10, 3), rep(0, 6)),
c(0, 0, sample(1:10, 5), rep(0, 3)),
c(rep(0, 6), sample(1:10, 4)),
c(0, 0, sample(1:10, 3), 0, sample(1:10, 2), 0, 0))
)
一个有限的解决方案是使用下面的 cumsum
来计算非零值,但当序列中有中断时不起作用,例如特定长度为 5 且组 d
被错误地包含在内。
library(dplyr)
df %>%
group_by(grp) %>%
mutate(cc = cumsum(x != 0)) %>% filter(cc == 5) %>% distinct(grp)
对于序列长度为 5 的示例,所需的输出将仅识别组 b
,而不是 d
。
最佳答案
您可以使用rle
为每个组查找连续的非零数字。
library(dplyr)
find_groups <- function(x, n) {
tmp <- rle(x != 0)
any(tmp$lengths[tmp$values] >= n)
}
#apply the function for each group
df %>%
group_by(grp) %>%
dplyr::filter(find_groups(x, 5)) %>%
ungroup %>%
distinct(grp)
# grp
# <chr>
#1 b
关于r - 识别哪个组包含非零值序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74440469/