使用均值按月对每日数据进行分组

时间:2021-04-04 19:54:57

标签: r dataframe aggregate mutate

我有一个大型数据集,如下所示,我想将每个国家/地区的每日数据转换为每月数据,同时获得 total_cases_per_million 和 stringency_index 的平均值。

head(datacovid)
 location                 date                         total_cases_per_million    stringency_index
 Afghanistan              24/02/2020                   0.026                      8.33
 Colombia                 25/02/2020                   0.026                      8.33
 Democratic Republic of Congo 26/02/2020               0.026                      8.33
 India                    27/02/2020                   0.026                      8.33
 Iraq                     28/02/2020                   0.026                      8.33
 Lebanon                  29/02/2020                   0.026                      8.33

结构如下:

<块引用>

str(datacovid) 'data.frame': 78444 obs。共 4 个变量: $ location : chr "阿富汗" "哥伦比亚" "刚果民主共和国" "印度" ... $ date : Factor w/ 455 levels "01/01/2020","01/01/2021",..: 348 363 378 393 408 423 5 20 35 50 ... $ total_cases_per_million:num 0.026 0.026 0.026 0.026 0.026 0.026 0.026 0.026 0.051 0.103 ... $ stringency_index : num 8.33 8.33 8.33 8.33 8.33 ...

我曾尝试在下面使用但失败了。非常感谢。

datacovid$date =  as.Date(datacovid$date, "%d/%m/%Y")
datacovid$month =  format(datacovid$date, "%b-%Y")
datacovid <- aggregate(cbind(total_cases_per_million, stringency_index) ~ month + location, datacovid, mean)

附言我是一个非常 R 的初学者。

1 个答案:

答案 0 :(得分:0)

您将日期列存储为一个因素。您可以将此列作为日期类型读取,也可以将其转换为 R 中的日期格式。

对于样本数据:

location <- c('Afghanistan', 'Colombia', ' Democratic Republic of Congo', 'India', 'Iraq', 'Lebanon', 'Lebanon')
date <- factor(c('24/02/2020', '25/02/2020', '26/02/2020', '27/02/2020', '28/02/2020', '26/02/2020', '27/02/2020'))
total_cases_per_million <- c(0.026, 0.026, 0.026, 0.026, 0.026, 0.026, 0.052)
stringency_index <- c(8.33, 8.33, 8.33, 8.33, 8.33, 8.33, 10.00)

datacovid <- data.frame(location, date, total_cases_per_million, stringency_index)

您可以获得每个国家的 total_cases_per_million 和 stringency_index 的月平均值,首先将日期列转换为 date 格式,然后您可以使用 dplyrgroup_by 函数。

datacovid$date = as.Date(datacovid$date, format = "%d/%m/%Y")

library(dplyr)

datacovid %>% 
    mutate(month = format(date, "%m")) %>%
        group_by(location, month) %>% 
            summarise(avg_total_cases_per_million=mean(total_cases_per_million), avg_stringency_index=mean(stringency_index))

这产生了输出:

output

或者您可以使用 lubridate 包从日期中提取月份,这样可以巧妙地做到这一点:

library(lubridate)

datacovid %>% 
    mutate(month = month(date)) %>%
        group_by(location, month) %>% 
            summarise(avg_total_cases_per_million=mean(total_cases_per_million), avg_stringency_index=mean(stringency_index))