【问题标题】:trying to create monthly total using R , but Sum() gives total bigger than actual尝试使用 R 创建每月总计,但 Sum() 给出的总计大于实际
【发布时间】:2017-09-20 07:40:10
【问题描述】:

我的数据叫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 次观察,因此很难检查。当我添加一些观察时,代码似乎对我有用。
  • 它的每日数据。完整数据在这里。 dropbox.com/s/0lyktc72ociouqr/Daily.csv?dl=0 ....请帮忙
  • 你的Date栏目比较混乱,日月月日不断变化,这肯定会影响润滑功能。
  • 理想情况下你应该 group_by(year,month) 否则会更高
  • 我也尝试过该选项,但仍然给出相同的值(即更高)

标签: r date dplyr lubridate


【解决方案1】:

处理日期问题的最简单方法是使用parse_date_time from 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
> 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多