Search code examples
rzoorollapply

Replace with 0 the first calculation in mutate and rollapply in R


i have a data frame in R called Data.

library(tibble)
library(dplyr)
library(zoo)
Data <- tibble(
  var = c("A", "A", "A", "A", "A","A"),
  val = c(1, 1, 1, 1, 1.5 , 1.5)
)%>%
  mutate( roll_sd   = rollapplyr(val, width = seq_len(n()), FUN = function(x) sd(x, na.rm = TRUE), fill = NA))
Data

with output :

# A tibble: 6 × 3
  var     val roll_sd
  <chr> <dbl>   <dbl>
1 A       1    NA    
2 A       1     0    
3 A       1     0    
4 A       1     0    
5 A       1.5   0.224
6 A       1.5   0.258

i want the first roll_sd other than 0 to be again 0 and then to continue as it is originally calculated. How can i do it in R ?

Ideally the outpout i want to be like this :

# A tibble: 6 × 3
  var     val roll_sd
  <chr> <dbl>   <dbl>
1 A       1    NA    
2 A       1     0    
3 A       1     0    
4 A       1     0    
5 A       1.5   0
6 A       1.5   0.258

Solution

  • Depending on what your answer is to my comment, I believe something like this may work for you:

    library(tibble)
    library(dplyr)
    library(zoo)
    
    Data <- tibble(
      var = c("A", "A", "A", "A", "A","A"),
      val = c(1, 1, 1, 1, 1.5 , 1.5)
    )%>%
      mutate( roll_sd   = rollapplyr(val, width = seq_len(n()), 
                                     FUN = function(x) sd(x, na.rm = TRUE), 
                                     fill = NA))
    
    Data <- rbind(Data, Data) # added so there are 2 places to be set to 0
    
    to_zero <- which(!is.na(Data$roll_sd) & Data$roll_sd > 0) # find all non-0 and non-NA numbers
    non_consecutive <- to_zero[c(TRUE, diff(to_zero) > 1)] # get every "first" non-0 number
    Data$roll_sd[non_consecutive] <- 0 # set to 0
    
    > Data
    
    # A tibble: 12 × 3
       var     val roll_sd
       <chr> <dbl>   <dbl>
     1 A       1    NA    
     2 A       1     0    
     3 A       1     0    
     4 A       1     0    
     5 A       1.5   0    
     6 A       1.5   0.258
     7 A       1    NA    
     8 A       1     0    
     9 A       1     0    
    10 A       1     0    
    11 A       1.5   0    
    12 A       1.5   0.258