在某些行之前删除观察

I have a data frame and I want to compute the mean across the variable value for all the period excluding +- two observations before/after that the crisis is 1 (i don't care about missing val). The calculation should be done by country (even though here in the example below I have only one country). Example:

country <- rep("AT",10)
value <- seq(1,10,1)
crisis <- c(0,0,0,NA,0,1,0,NA,0,0)

df <- data.frame(country, value, crisis)
df


mean(df$value[df$crisis == 0], na.rm=TRUE)

# expected result

exp_mean <- (1+2+3+9+10)/5
exp_mean
评论
  • 哼,涐吐
    哼,涐吐 回复

    We can write a function which excludes the variables which are +- 2 observations after crisis = 1.

    custom_mean <- function(c, v) {
       inds <- which(c == 1)
       mean(v[-unique(c(sapply(inds, `+`, -2:2)))], na.rm = TRUE)
    }
    

    and apply it for each country.

    library(dplyr)
    df %>% group_by(country) %>% summarise(exp_mean = custom_mean(crisis, value))
    
    # A tibble: 1 x 2
    #  country exp_mean
    #  <fct>      <dbl>
    #1 AT             5