簡體   English   中英

將每日數據匯總到月/年間隔

[英]Aggregate Daily Data to Month/Year intervals

我不經常在R中使用日期,但我想這很容易。 我有一個代表數據框中日期的列。 我只是想創建一個新的數據框,使用日期按月/年匯總第二列。 什么是最好的方法?

我想要第二個數據幀,以便將其提供給繪圖。

您將提供的任何幫助將不勝感激!

編輯:供參考:

> str(temp)
'data.frame':   215746 obs. of  2 variables:
 $ date  : POSIXct, format: "2011-02-01" "2011-02-01" "2011-02-01" ...
 $ amount: num  1.67 83.55 24.4 21.99 98.88 ...

> head(temp)
        date amount
1 2011-02-01  1.670
2 2011-02-01 83.550
3 2011-02-01 24.400
4 2011-02-01 21.990
5 2011-02-03 98.882
6 2011-02-03 24.900

我會用lubridateplyr ,將日期舍入到最接近的月份,以便更容易繪制:

library(lubridate)
df <- data.frame(
  date = today() + days(1:300),
  x = runif(300)
)
df$my <- floor_date(df$date, "month")

library(plyr)
ddply(df, "my", summarise, x = mean(x))

可能有一個更優雅的解決方案,但是使用strftime()然后aggregate()分為幾個月和幾年應該這樣做。 然后重新組裝繪圖日期。

x <- as.POSIXct(c("2011-02-01", "2011-02-01", "2011-02-01"))
mo <- strftime(x, "%m")
yr <- strftime(x, "%Y")
amt <- runif(3)
dd <- data.frame(mo, yr, amt)

dd.agg <- aggregate(amt ~ mo + yr, dd, FUN = sum)
dd.agg$date <- as.POSIXct(paste(dd.agg$yr, dd.agg$mo, "01", sep = "-"))

游戲有點晚了,但另一種選擇是使用data.table

library(data.table)
setDT(temp)[, .(mn_amt = mean(amount)), by = .(yr = year(date), mon = months(date))]

# or if you want to apply the 'mean' function to several columns:
# setDT(temp)[, lapply(.SD, mean), by=.(year(date), month(date))]

這給了:

     yr      mon mn_amt
1: 2011 februari 42.610
2: 2011    maart 23.195
3: 2011    april 61.891

如果你想要幾個月的名字而不是數字,你可以使用:

setDT(temp)[, date := as.IDate(date)
            ][, .(mn_amt = mean(amount)), by = .(yr = year(date), mon = months(date))]

這給了:

     yr      mon mn_amt
1: 2011 februari 42.610
2: 2011    maart 23.195
3: 2011    april 61.891

如您所見,這將以您的系統語言(在我的情況下為荷蘭語)中給出月份名稱。


或者使用lubridatedplyr的組合:

temp %>% 
  group_by(yr = year(date), mon = month(date)) %>% 
  summarise(mn_amt = mean(amount))

使用數據:

# example data (modified the OP's data a bit)
temp <- structure(list(date = structure(1:6, .Label = c("2011-02-01", "2011-02-02", "2011-03-03", "2011-03-04", "2011-04-05", "2011-04-06"), class = "factor"), 
                       amount = c(1.67, 83.55, 24.4, 21.99, 98.882, 24.9)), 
                  .Names = c("date", "amount"), class = c("data.frame"), row.names = c(NA, -6L))

只需使用xts包就可以了。

library(xts)
ts <- xts(temp$amount, as.Date(temp$date, "%Y-%m-%d"))

# convert daily data
ts_m = apply.monthly(ts, FUN)
ts_y = apply.yearly(ts, FUN)
ts_q = apply.quarterly(ts, FUN)

其中FUN是一個匯總數據的函數(例如sum)

你可以這樣做:

short.date = strftime(temp$date, "%Y/%m")
aggr.stat = aggregate(temp$amount ~ short.date, FUN = sum)

我有一個函數monyr ,我用於這種東西:

monyr <- function(x)
{
    x <- as.POSIXlt(x)
    x$mday <- 1
    as.Date(x)
}

n <- as.Date(1:500, "1970-01-01")
nn <- monyr(n)

您可以將as.Date更改為as.POSIXct以匹配數據中的日期格式。 按月匯總只是使用aggregate / by / etc。

此外,鑒於您的時間序列似乎是xts格式,您可以使用平均函數將您的每日時間序列匯總到每月時間序列,如下所示:

d2m <- function(x) {
  aggregate(x, format(as.Date(zoo::index(x)), "%Y-%m"), FUN=mean)
}

這是一個dplyr選項:

library(dplyr)

df %>% 
  mutate(date = as.Date(date)) %>% 
  mutate(ym = format(date, '%Y-%m')) %>% 
  group_by(ym) %>% 
  summarize(ym_mean = mean(x))

還有一個解決方案

 rowsum(temp$amount, format(temp$date,"%Y-%m"))

對於情節,您可以使用barplot

barplot(t(rowsum(temp$amount, format(temp$date,"%Y-%m"))), las=2)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM