我有一个看起来像这样的数据框(让我们称之为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
我希望这是有道理的。我在stackoverflow上找不到任何与日期一起工作的东西,尝试做类似的事情(除非我正在搜索错误的函数)。非常感谢!
答案 0 :(得分:4)
我在您的数据集中创建了一个仅包含年份和月份的单独列。然后,我在该列上做了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))
答案 1 :(得分:1)
我设法使用所有dplyr函数,在@ user108636
的帮助下完成df %>%
select(Date, Price) %>%
arrange(Date) %>%
mutate(Month_Year = substr(Date, 1,7)) %>%
group_by(Month_Year) %>%
summarise(mean(Price, na.rm = TRUE))
select函数选择日期和价格列。 排列函数根据日期排列我的数据框 - 最早的日期是第一个。 mutate函数添加了另一个列,它排除了那一天并离开了我们,例如......
Month_Year
2015-10
2015-10
2015-11
2015-12
2015-12
按功能分组将所有月份组合在一起,汇总功能计算每个月的平均价格。
答案 2 :(得分:1)
为了完整起见,这里还有一个Messenger -> your api server ->api.ai nlp -> your webhook /end point
解决方案:
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
答案 3 :(得分:0)
这应该是按月 - 月的价格数据。
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)