[英]Using R: How do I count the number of elements falling into specific bins while grouping these counted numbers per year?
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.我正在处理每日温度数据(设置为年-月-日样式的日期),我使用 c(-20,-10,0,10,20,30,40) 作为中断将这些数据放入温度箱中。 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:通过使用以下方法,我得到了包含 1980 年到今天时间跨度的所有天数的表格:
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.我是 R 的新手,所以我的问题的答案可能有点明显。 Nevertheless, thanks in advance!尽管如此,还是先谢谢了!
You need year
to get the year of the date, and table
to count the observation.您需要year
来获取日期的年份,并需要table
来计算观测值。
library(lubridate)
with(df, table(year(date), bin))
bin
(-10,0] (0,10]
1980 4 2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.