尝试使用R创建每月总计,但Sum()总计大于实际

时间:2017-09-20 07:40:10

标签: r date dplyr lubridate

我的数据称为aphro,是每日降水

 Date          Terai+Siwalik    Hilly 
  <dttm>           <dbl>        <dbl>       
1 1951-01-01         1.92201    1.16439    
2 1951-02-01         0.00000    0.00000   
3 1951-03-01         0.00000    0.00000    
4 1951-04-01         0.00000    0.00000    
5 1951-05-01         0.00000    0.00000     
6 1951-06-01         0.00000    0.00000     

我正在尝试查找每月总计,而我的代码是

aphro_m <- aphro %>%
mutate(month =month(Date), year = year(Date)) %>%
group_by(month, year) %>%
summarise(total_TaS =sum(`Terai+Siwalik`), Date =first(Date)
)

但是我检查时的输出高于实际值?

请帮忙。

1 个答案:

答案 0 :(得分:0)

处理日期问题的最简单方法是使用parse_date_time中的lubridate

> aphro %>%
+   as_data_frame %>%
+   mutate(Date = parse_date_time(Date, c("dmy", "mdy")),
+          Month = month(Date), Year = year(Date)) %>%
+   group_by(Month, Year) %>%
+   summarise(total_TaS =sum(`Terai.Siwalik`), Date=first(Date)) %>%
+   ungroup()
# A tibble: 768 x 4
   Month  Year total_TaS       Date
   <dbl> <dbl>     <dbl>     <dttm>
 1     1  1951 16.057931 1951-01-01
 2     1  1952  5.101386 1952-01-01
 3     1  1953 45.921963 1953-01-01
 4     1  1954 29.684509 1954-01-01
 5     1  1955 20.141103 1955-01-01
 6     1  1956 26.096579 1956-01-01
 7     1  1957 70.174464 1957-01-01
 8     1  1958 26.157329 1958-01-01
 9     1  1959 72.161088 1959-01-01
10     1  1960  2.401913 1960-01-01
# ... with 758 more rows
>