首页 文章

用dplyr和lsfit滚动回归

提问于
浏览
0

我正试图用 dplyr 进行滚动回归 . 我正在使用包 zoolsfit 中的 rollapplyr 作为我尝试过的'm only interested in the beta of the regression. Here':

library(dplyr); library(zoo)

df1 = expand.grid(site = seq(10),
                    year = 2000:2004,
                    day = 1:50)

df1 %>%
group_by(year) %>%
mutate(beta1 = rollapplyr(data = site,
                            width = 5,
                            FUN = lsfit,
                            x=day))

我收到此错误: Error: not all arguments have the same length

我认为 rollapplyr 接受非动物园对象,但我可能错了 . 也可能是管道( %>% )与 rollapplyr 不能很好地兼容,因为它需要函数中的数据对象 .

任何的想法?

EDIT 我的问题不同于:rolling regression with dplyr我想使用管道才能使用 group_by

1 回答

  • 3

    该函数不会循环通过多个向量 . 将切片的 site 向量与完整向量 day 进行比较 . 我们可以使用 Map 编写我们自己的滚动应用函数来遍历我们的向量组:

    rollapplydf <- function(xx, width) {
      l <- length(xx)
      sq <- Map(':', 1:(l-width+1), width:l)
      lst <- lapply(sq, function(i) lm(xx[i] ~ seq(length(xx[i])))$coeff[2] )
      do.call('rbind', c(rep(NA, width-1L), lst))
    }
    

    所以我们可以将它添加到管道中:

    library(dplyr)
    df1 %>% 
      group_by(year) %>% 
      mutate(beta1 = rollapplydf(xx = site, width = 5) )
    
    # Source: local data frame [2,500 x 4]
    # Groups: year [5]
    # 
    #     site  year   day beta1
    #    (int) (int) (int) (dbl)
    # 1      1  2000     1    NA
    # 2      2  2000     1    NA
    # 3      3  2000     1    NA
    # 4      4  2000     1    NA
    # 5      5  2000     1     1
    # 6      6  2000     1     1
    # 7      7  2000     1     1
    # 8      8  2000     1     1
    # 9      9  2000     1     1
    # 10    10  2000     1     1
    # ..   ...   ...   ...   ...
    

相关问题