简体   繁体   中英

R rolling count of positive values

在此处输入图片说明

I have the X column in a dataframe and want to create the RolPos. The RolPos column is the rolling count of positive values having a 3 rows rolling window. Any help how could I do that?

Data to be used:

df <- data.frame(x = c(0, 1, -3, -1, 1, -5, 3, -2))

I would suggest this slider approach with a function to count positive values:

library(slider)
library(dplyr)
#Data
df <- data.frame(x=c(0,1,-3,-1,1,-5,3,-2))
#Function
getpos <- function(x) 
{
  y <- length(which(x>0))
  return(y)
}
# Rolling by group
df %>% 
  mutate(rolling = slide_dbl(x, getpos, .before = 2, .complete = FALSE))

Output:

   x rolling
1  0       0
2  1       1
3 -3       1
4 -1       1
5  1       1
6 -5       1
7  3       2
8 -2       1

You can cbind the lagged x and make then rowSums .

n <- length(x)
rowSums(cbind(x, c(0, x[1:(n-1)]), c(0, 0, x[1:(n-2)])) > 0)
#[1] 0 1 1 1 1 1 2 1

You can use runner . For more cases see the documentation and vignettes.

library(runner)
library(dplyr)

df <- data.frame(x = c(0, 1, -3, -1, 1, -5, 3, -2))

df %>%
  mutate(
    RolPos = runner(
      x = df$x,
      f = function(x) {
        sum(x > 0)  
      },
      k = 3
    )    
  )

# x RolPos
# 1  0      0
# 2  1      1
# 3 -3      1
# 4 -1      1
# 5  1      1
# 6 -5      1
# 7  3      2
# 8 -2      1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM