考虑到缺失值,如何计算15年中31天的每日平均值?

时间:2015-12-29 16:05:34

标签: r

This question被标记为重复。

的具体问题我不认为它是重复的
  • 在几天内测量的时间跨度上的平均值
  • 和缺少数据

其他地方没有处理过。 我已经做了一个答案,我不允许在原始问题中粘贴。所以我把它贴在这里。

  

根据15 years from 1993 to 2008的每日数据。如何根据以感兴趣的当天为中心的31天窗口,计算一年中每一天的文件中变量Open的每日平均值。因此,15⨯31 = 465 dates有助于统计一天。

     

在15年中,输出只是365个值

     

该文件可以从这里下载:   http://chart.yahoo.com/table.csv?s=sbux&a=2&b=01&c=1993&d=2&e=01&f=2008&g=d&q=q&y=0&z=sbux&x=.csv

1 个答案:

答案 0 :(得分:2)

加载包和数据

find . -iname "*.php" -print -exec sed -i -e '/^\/\###--X--###/,/^\/\/###--X--###/d' '{}' \;

lubridate包有一个很好的函数ddays(),它增加了几天。它涉及2月29日。例如

library(lubridate)
library(dplyr)
dtf <- read.csv("http://chart.yahoo.com/table.csv?s=sbux&a=2&b=01&c=1993&d=2&e=01&f=2008&g=d&q=q&y=0&z=sbux&x=.csv", stringsAsFactors = FALSE)
# I prefer lower case column names
names(dtf) <- tolower(names(dtf))    

将减去15和15的日期添加到数据集中,这些将是给定年份中给定日期应计算平均值的时间范围。

ymd("2008-03-01") - ddays(15)
# [1] "2008-02-15 UTC"
ymd("2007-03-01") - ddays(15)
# [1] "2007-02-14 UTC"

创建一个函数,给出给定日期内所有这15年的平均值:

dtf <- dtf %>% 
    mutate(date = ymd(date),
           minus15 = date - ddays(15),
           plus15 = date + ddays(15),
           monthday = substr(as.character(date),6,10),
           year = year(date),
           plotdate = ymd(paste(2008,monthday,sep="-"))) 

calendardays <- dtf %>% 
    select(monthday) %>% 
    distinct() %>%
    arrange(monthday) 

在日历中可用的所有日期使用该功能:

meanday <- function(givenday, dtf){
    # Extract the given day minus 15 days in all years available
    # Day minus 15 days will differ for example for march first 
    # in years where there is a february 29
    lowerbound <- dtf$minus15[dtf$monthday == givenday]
    # Produce the series of 31 days around the given day
    # that is the lower bound + 30 days
    filterdates <- lapply(lowerbound, function(x) x + ddays(0:30))
    filterdates <- Reduce(c, filterdates)
    # filter all of these days 
    dtfgivenday <- dtf %>%
        filter(date %in% filterdates) 
    return(mean(dtfgivenday$open))
}

图解

meandays <- sapply(calendardays$monthday, meanday, dtf)
calendardays <- calendardays %>% 
    mutate(mean = meandays,
           plotdate = ymd(paste(2008,monthday,sep="-")))

Time series

All series on one year

Plot of the moving average

看到这里出现周期性是否很奇怪?

相关问题