how can I calculate mean of every 6 rows in a data frame based on the condition of other column?

I have a dataframe in R, contain 3000 rows and 2 columns (temp, flag), I am trying to calculate "meantemp" as the third column for every 6 rows if the corresponding values in flag column are not NA, SO if flage values are equal to NA I want to show in the meantemp column NA value. sorry for this question.

1 answer

  • answered 2021-01-11 05:30 Ronak Shah

    You can try :

    library(dplyr)
    
    df %>%
      group_by(group = ceiling(row_number()/6)) %>%
      mutate(meantemp = if(all(is.na(flag))) mean(temp, na.rm = TRUE) else NA) %>%
      ungroup() %>%
      select(-group) -> df