[英]rollapply regression “envir” error
I have this data set https://gist.github.com/natemiller/42eaf45747f31a6ccf9a 我有这个数据集https://gist.github.com/natemiller/42eaf45747f31a6ccf9a
I'm trying to apply a rolling regression using the rollapply
in the zoo package, following the examples in the rollapply
help and keep getting what I imagine is a simple error, but one I haven't been able to work around. 我正在尝试使用
rollapply
在动物园包中应用滚动回归,遵循rollapply
帮助中的示例并继续得到我想象的简单错误,但我rollapply
这个问题。
If I load the above data as "dat" then I do this.. 如果我将上述数据加载为“dat”,那么我这样做..
dat$Date<-as.POSIXct(dat$Date, format="%m/%d/%y %H:%M")
library(zoo)
roll<-rollapply(dat, width = 6, FUN = function(d) coef(lm(Temp~Date, data=d)), align="right")
and I get the error 我得到了错误
Error in eval(predvars, data, env) : invalid 'envir' argument
dat
should be an appropriate input to lm
, this lm
works outside of rollapply
, so the error arises in the rollapply
itself. dat
应该是lm
的适当输入,这个lm
在rollapply
之外工作,因此错误出现在rollapply
本身。 I assume its simple, but I'd appreciate help. 我认为它很简单,但我很感激帮助。 Thanks
谢谢
First of all , I don't think that what you do make sense. 首先,我认为你所做的事情没有意义。 You try to do a regression with 6 values .
您尝试使用6个值进行回归 。
The error occurs because you don't give a good environnment for lm
. 发生错误是因为您没有为
lm
提供良好的环境。 The d is a an atomic vector of length 6, or you need a data.frame with 2 columns Temp and date. d是一个长度为6的原子向量,或者你需要一个带有2列Temp和date的data.frame。 For example , the first d is :
例如,第一个d是:
d
9.5 9.5 9.5 9.5 9.5 9.5
Applying lm
with this d , you reproduce the error: 使用此d应用
lm
,您重现错误:
lm(Temp~Date, data=d)
Error in eval(predvars, data, env) :
numeric 'envir' arg not of length one
you don't have the Date
of the current roll window, you have just the values. 如果没有当前滚动窗口的
Date
,则只有值。
Try this: 尝试这个:
library(zoo)
dat <- read.zoo("sampleTempData.csv", header = TRUE, sep = ",",
index = 2, tz = "", format = "%m/%d/%y %H:%S")
Seq <- zoo(seq_along(dat), time(dat))
coefs <- rollapply(Seq, 6, function(ix) coef(lm(dat ~ time(dat), subset = ix)))
ADDED: poster added to question so additional code here. 添加:海报添加到问题所以这里的附加代码。 Note that we are using
POISIXct
for date/times so time units associated with the coefs
zoo object are in seconds regardless of the input format. 请注意,我们使用
POISIXct
作为日期/时间,因此与coefs
zoo对象关联的时间单位以秒为单位,与输入格式无关。 At the end we convert from seconds to days. 最后我们将秒数转换为数天。 See
?aggregate.zoo
看
?aggregate.zoo
colnames(coefs) <- c("Intercept", "slope")
Seq.coefs <- zoo(1:nrow(coefs), time(coefs))
max.coefs <- function(ix) coefs[which.max(coefs[ix, 2]), ]
ag <- aggregate(Seq.coefs, as.Date, max.coefs)
transform(ag, slope = slope * 24 * 3600)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.