Emil Krabbe
Emil Krabbe

Reputation: 101

Counting values above certain threshold every nth cell

I have a 7700 x 93 dataframe. I want a 1100 x 93 dataframe that with a 7 day gap counts how many instances are above a certain threshold (here 30):

What I have:

  daily_temp_first_two_weeks <- data.frame(
      daily_temp = c(24,25,31,32,21,23,31,34,21,23,43,12,29,23))
      
daily_temp_first_two_weeks
daily_temp
1          24
2          25
3          31
4          32
5          21
6          23
7          31
8          34
9          21
10         23
11         43
12         12
13         29
14         23

What I want:

 number_of_days_above_30_per_week <- data.frame(
      noda30pw = c(3,2)
    ) 
    
    number_of_days_above_30_per_week
number_of_days_above_30_per_week
  noda30pw
1        3
2        2

Upvotes: 0

Views: 33

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 389055

You can create a group of every 7 days and count number of values greater than 30 in them.

tapply(daily_temp_first_two_weeks$daily_temp > 30, 
       ceiling(seq(nrow(daily_temp_first_two_weeks))/7), sum)

#1 2 
#3 2 

Using dplyr :

library(dplyr)

daily_temp_first_two_weeks %>%
  group_by(week = ceiling(row_number()/7)) %>%
  summarise(noda30pw = sum(daily_temp > 30))

#   week noda30pw
#  <dbl>    <int>
#1     1        3
#2     2        2

Upvotes: 1

Related Questions