Home > Back-end >  Using R: How do I count the number of elements falling into specific bins while grouping these count
Using R: How do I count the number of elements falling into specific bins while grouping these count

Time:03-29

I am working with daily temperature data (set as dates in a year-month-day style) which I have binned in temperature bins using c(-20,-10,0,10,20,30,40) as breaks. I now have a data frame looking like that

    date         meantemp      bin
1 1980-01-01     -0.1026295  (-10,0]
2 1980-01-02     -0.8921732  (-10,0]
3 1980-01-03     -2.9833818  (-10,0]
4 1980-01-04     -0.6400758  (-10,0]
5 1980-01-05      2.0644677   (0,10]
6 1980-01-06      2.5712572   (0,10]

I got the table with the number of all days for the time span 1980 to today by using :

Summary(df %>% filter(date >= as.Date('1980-01-01') & date <= as.Date('1980-12-31')))


date                meantemp        temp_bin  

Min.   :1980-01-01   Min.   :-8.004   (-20,-10]:  0  

1st Qu.:1980-04-01   1st Qu.: 3.695   (-10,0]  : 40  
Median :1980-07-01   Median : 8.323   (0,10]   :160  

Mean   :1980-07-01   Mean   : 8.524   (10,20]  :155  

3rd Qu.:1980-09-30   3rd Qu.:14.029   (20,30]  : 11  

Max.   :1980-12-31   Max.   :22.560   (30,40]  :  0  

Now, is there a way I can create a table that gives me the number of days in each bin per year?

I am looking for something like this:

       (-20,-10] (-10,0]   (0,10]   (10,20]    (20,30]    (30,40]

1980       0          40      160       155        11         0
1981        5        50       100       150        57         3

I am new to R so the answer to my question might be a bit obvious. Nevertheless, thanks in advance!

CodePudding user response:

You need year to get the year of the date, and table to count the observation.

library(lubridate)

with(df, table(year(date), bin))

      bin
       (-10,0] (0,10]
  1980       4      2
  • Related