解决此问题的一种方法是使用dplyr包以创建一个新列,指示当前行是否对应于新“计数期”的开始(即,当信号1是 1).然后您可以使用润滑剂包以创建一个新列,指示每个计数期的持续时间。最后,您可以使用 dplyr 按计数周期的持续时间对数据进行分组,然后使用 summarize 函数统计每组内的行数。
这是您如何执行此操作的示例:
library(tibble)
library(dplyr)
library(lubridate)
set.seed(1234)
df <- tibble(signal1 = c(0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0),
signal2 = rbinom(31, 1, 0.7),
signal3 = c(0, 0, 1, 2, 0, 0, 0, 0, 0, 1, 2, 3, 4, 0, 1, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 0, 0, 0, 0, 1, 2))
# Create a new column indicating whether the current row is the start of a new counting period
df <- df %>%
mutate(start_period = ifelse(signal1 == 1, 1, 0))
# Create a new column indicating the duration of each counting period
df <- df %>%
group_by(start_period) %>%
mutate(duration = seconds_to_period(sum(seconds(1))))
# Group the data by the duration of the counting period and count the number of rows within each group
df %>%
group_by(duration) %>%
summarize(count = n())
这应该会给你你正在寻找的计数。请注意,此解决方案假定信号1在新的计数周期开始时始终为 1,并且信号2在计数周期结束时始终为 0。如果不是这种情况,您可能需要相应地调整代码。