简体   繁体   English

R在处理时间序列(ts)对象而不是data.frame时出错

[英]R Error when adressing time series (ts) object instead of data.frame

I want to use a time series object (because I want to use lag() later) but I am not able to adress the time series object in a function: 我想使用时间序列对象(因为稍后要使用lag()),但无法在函数中处理时间序列对象:

With a data.frame it does not matter whether I code 使用data.frame无论我是否编码

dat=data.frame(x=c(1,2,3,4,5,6))
sum(2*dat[,"x"])

[1] 42

or alternatively 或者

with(dat,sum(2*x))

[1] 42

But as soon as I transform the data.frame into a time series object the function does not work anymore. 但是,一旦我将data.frame转换为时间序列对象,该函数便不再起作用。

dat=data.frame(x=c(1,2,3,4,5,6))
dat <- ts(dat)
sum(2*dat[,"x"])

[1] 42

so this still works, but 所以这仍然有效,但是

with(dat,sum(2*x))

now results in an 现在导致

Error in eval(substitute(expr), data, enclos = parent.frame()) : 
  numeric 'envir' arg not of length one

Or to put it in other words: With the ts-object I cannot use any functions like 或者换句话说:对于ts对象,我不能使用任何函数,例如

testy <- function(data,par){
  with(data,sum(par * x))
}
sapply(data=dat,2,testy)

without getting that error "numeric 'envir' arg not of length one" whereas df-objects do not cause that error. 不会出现“长度不为1的数字'envir'arg'”错误,而df对象不会导致该错误。 But I need ts() later for the lag() function. 但是我稍后需要ts()来用于lag()函数。

What can I do to use time series objects within a function? 如何在函数中使用时间序列对象?

We could convert it to zoo and it has with as one of its methods 我们可以将其转换为zoo ,它有with它作为一个methods

library(zoo)
methods(class = 'zoo')
with(zoo(dat), sum(2 * x))
# [1] 42

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM