【发布时间】:2013-04-30 04:32:07
【问题描述】:
我正在尝试创建一个自动创建zoo 对象的多项式的函数。来自 Python 的典型方法是在 for 循环外创建一个列表,然后将列表附加到循环内。在此之后,我在 R 中编写了以下代码:
library("zoo")
example<-zoo(2:8)
polynomial<-function(data, name, poly) {
##creating the catcher object that the polynomials will be attached to
returner<-data
##running the loop
for (i in 2:poly) {
#creating the polynomial
poly<-data^i
##print(paste(name, i), poly) ##done to confirm that paste worked correctly##
##appending the returner object
merge.zoo(returner, assign(paste(name, i), poly))
}
return(returner)
}
#run the function
output<-polynomial(example, "example", 4)
但是,当我运行该函数时,R 不会抛出异常,但输出对象除了我最初在 example zoo 对象中创建的数据之外没有任何其他数据。我怀疑我误解了merge.zoo 或者现在允许动态重新分配循环内多项式的名称。
想法?
【问题讨论】:
-
试试这个:
ans <- do.call(merge, lapply(1:4, function(i) example^i))或者这个:ans <- zoo(poly(example, 4, raw = TRUE), time(example))或者这个:z <- lag(example, rep(0, 4)); ans <- z ^ col(z)。在每种情况下,通过设置名称来跟随它:names(ans) <- 1:4。