【问题标题】:Using merge.zoo to dynamically create variables in R使用 merge.zoo 在 R 中动态创建变量
【发布时间】: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 &lt;- do.call(merge, lapply(1:4, function(i) example^i)) 或者这个:ans &lt;- zoo(poly(example, 4, raw = TRUE), time(example)) 或者这个:z &lt;- lag(example, rep(0, 4)); ans &lt;- z ^ col(z)。在每种情况下,通过设置名称来跟随它:names(ans) &lt;- 1:4

标签: r function for-loop zoo


【解决方案1】:

至于代码中的错误,您缺少从merge.zooreturner 的结果分配。 但是,我认为有更好的方法来实现您想要的。

example <- zoo(2:8)

polynomial <- function(data, name, poly) {

    res <- zoo(sapply(1:poly, function(i) data^i))
    names(res) <- paste(name, 1:4)
    return(res)
}

polynomial(example, "example", 4)
##   example 1 example 2 example 3 example 4
## 1         2         4         8        16
## 2         3         9        27        81
## 3         4        16        64       256
## 4         5        25       125       625
## 5         6        36       216      1296
## 6         7        49       343      2401
## 7         8        64       512      4096

【讨论】:

  • 谢谢!我必须对sapply 进行更多阅读,但它就像一个魅力。
猜你喜欢
  • 2014-09-02
  • 2021-08-13
  • 1970-01-01
  • 2019-07-25
  • 2013-06-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多