如何使用 dplyr 在 R 中按日期过滤并将月份组合在一起

How to filter by dates and grouping months together in R using dplyr

我有一个看起来像这样的数据框(我们称之为 df1)...

Date          Price
2014-08-06       22
2014-08-06       89
2014-09-15       56
2014-06-04       41
2015-01-19       11
2015-05-23        5
2014-07-21      108

数据框中还有其他变量,但我们暂时忽略它们,因为我不需要它们。

我之前使用

订购过
df2 <- df1[order(as.Date(df1$Date, format="%Y/%m/%d")),]

然后创建了一个仅包含一个月值的数据框,例如,仅包含 2015 年 9 月的日期...

september2015 <- df2[df2$Date >= "2015-09-01" & df2$Date <= "2015-09-30",]

我在 2015 年和 2014 年的所有月份都这样做了。 然后我需要在给定的每个月内创建平均价格。我已经完成了...

mean(september2015$Price, na.rm = TRUE)

显然,这是非常冗长乏味的,涉及到很多行代码。我正在尝试通过使用 dplyr 包来提高我的代码的效率。

到目前为止我已经...

datesandprices <- select(df2, Date, Price)

datesandprices <- arrange(datesandprices, Date)

summarise(datesandprices, avg = mean(Price, na.rm = TRUE))

或者更简单的形式...

df1 %>%
    select(Date, Price) %>%
    arrange(Date) %>%
    filter(Date >= 2014-08-06 & Date =< 2014-08-30)
    summarise(mean(Price, na.rm = TRUE))

过滤行对我不起作用,我不知道如何使用此方法按日期过滤。我想得到每个月的平均值,而不必一个一个地计算它——理想情况下,将每月的平均值提取到一个新的数据框或列中,看起来像...

Month         Average
Jan 2014         x
Feb 2014         y
...
Nov 2015         z
Dec 2015         a

我希望这是有道理的。我在 Whosebug 上找不到任何与日期一起使用的东西,试图做类似的事情(除非我正在搜索错误的函数)。非常感谢!

我在你的数据集中做了一个单独的列,只包含年份和月份。然后,我在该列上做了一个 group_by 以获得每个月的平均值。

Date <- c("2014-08-06", "2014-08-06", "2014-09-15", "2014-06-04", "2015-01-19", "2015-05-23", "2014-07-21")
Price <- c(22,89,56,41,11,5,108)

Date <- as.Date(Date, format="%Y-%m-%d")

df <- data.frame(Date, Price)
df$Month_Year <- substr(df$Date, 1,7)
library(dplyr)

df %>%
  #select(Date, Price) %>%
  group_by(Month_Year) %>%
  summarise(mean(Price, na.rm = TRUE))

在 @user108636

的帮助下,我设法使用所有 dplyr 函数完成了它
df %>%
    select(Date, Price) %>%
    arrange(Date) %>%
    mutate(Month_Year = substr(Date, 1,7)) %>%
    group_by(Month_Year) %>%
    summarise(mean(Price, na.rm = TRUE))

select 函数 selects 日期和价格列。 安排功能根据日期安排我的数据框 - 最早的日期排在第一位。 mutate 函数添加了另一列,该列排除了日期并留给我们,例如...

Month_Year
2015-10
2015-10
2015-11
2015-12
2015-12

group by 函数将所有月份分组在一起,summarize 函数计算每个月价格的平均值。

这应该是指您按月-年的价格数据。

library(zoo)

#Pull out columns
Price<-df1["Price"]
Date<-df1["Date"]

#Put in Zoo
zooPrice <- zoo(Price,Date)

#Monthly mean with year (vector)
monthly.avg <- apply.monthly(zooPrice, mean)

#function to change back to DF
zooToDf <- function(z) {
    df <- as.data.frame(z) 
    df$Date <- time(z) #create a Date column
    rownames(df) <- NULL #so row names not filled with dates
    df <- df[,c(ncol(df), 1:(ncol(df)-1))] #reorder columns so Date first
    return(df)
}

#Apply function to create new Df with data!
MonthYearAvg<-zooToDf(monthly.avg)

为了完整起见,这里还有一个data.table解决方案:

library(data.table)

# in case  Date is of type character
setDT(df1)[, .(Average = mean(Price, na.rm = TRUE)), keyby = .(Yr.Mon = substr(Date, 1,7))]

# in case Date is of class Date or POSIXct
setDT(df2)[, .(Average = mean(Price, na.rm = TRUE)), keyby = .(Yr.Mon = format(Date, "%Y-%m"))]
    Yr.Mon Average
1: 2014-06    41.0
2: 2014-07   108.0
3: 2014-08    55.5
4: 2014-09    56.0
5: 2015-01    11.0
6: 2015-05     5.0

请注意,分组变量 Yr.Mon 是在 keyby 子句中“即时”创建的。

数据

library(data.table)
df1 <- fread(
  "Date          Price
2014-08-06       22
2014-08-06       89
2014-09-15       56
2014-06-04       41
2015-01-19       11
2015-05-23        5
2014-07-21      108")
df2 <- df1[, Date := as.Date(Date)]