COUNTIF在移动的窗口上

时间:2019-08-28 00:47:54

标签: rstudio

我有一列,其中为数据点分配了“ 1”或“ 2”。我想在Excel中使用类似于COUNTIF的功能,但是要在移动的窗口上使用,例如= COUNTIF(G2:G31,2)以确定在给定窗口中存在多少个“ 2”

snap

1 个答案:

答案 0 :(得分:0)

您也许可以使用tibbletime

1)由于您对状态为12感兴趣,因此我们可以将其重新编码为逻辑(布尔值)。假设您的data.frame名为df

df$state <- df$state == 2

2)逻辑很酷,因为我们可以简单地对其求和,并获得TRUE值的数量:

# total number of rows with state == 2:
sum(df$state)

3)进行滚动功能,请参见。链接:

library(tibbletime)
rolling_sum <- rollify(sum, window = 30)
df$countif = rolling_sum(df$state)

但是,这种方法不能解决前29行。对于那些您可以使用的情况:

df$countif[1:29] <- cumsum(df$state[1:29])