Error with xts::apply: “Error in coredata.xts(x) : currently unsupported data type”

社会主义新天地 提交于 2019-12-10 10:09:48

问题


The error occurred to me When I was trying to do the following work:

# generate random integrals #
data <- xts(floor(runif(100, 1,101)),as.Date("1973-02-01") + c(1:100) - 1)
apply.monthly(data, diff,1,1)

, while this one works:

apply.monthly(data,mean)

I have checked similar questions posted, but it seems they do not apply to the situation here.

Any advice?


Some further explanation:

The reason I need this is that I got a time series data set like the following,

1990-05 100
1990-04 80
1990-03 60
1990-02 20
1990-01 5
1989-12 110
1989-11 89
1989-10 78
...

In each year, y(t)=y_(t-1)+dy, where dt is value change in period t. But this pattern only happens in each year and each year separately. So basically, I want to retrieve the difference between each month in every specific year, that is:

1990-05 20  #100-80
1990-04 20  #80-60
1990-03 40  #60-20
1990-02 15  #20-5
1990-01 5   #5
1989-12 21  #110-89
1989-11 11  #89-78  
...

Hope I have made the explanation clear enough.

Thanks,


回答1:


apply.monthly and period.apply are used to aggregate data to the specified period. diff doesn't work because diff.xts returns a vector the same length as the input. mean works because it returns one value for a given input vector.

It's not clear to me what you expect apply.monthly(data, diff) to do. It would be the same as calling diff(data) and then adding NA to the first value of each month.


With your edit, I now understand what you are trying to do. You want the differences, but you want January of each year to be the level for that month, not the difference from December of the prior year.

Here's one way to do it:

# Load your data as an example
Lines <- 
"1990-05 100
1990-04 80
1990-03 60
1990-02 20
1990-01 5
1989-12 110
1989-11 89
1989-10 78"
con <- textConnection(Lines)
# Ensure the timezone of your non-intraday xts object is UTC,
# or bad things can happen
x <- as.xts(read.zoo(con, FUN=as.yearmon), tzone="UTC")
close(con)

# Create a helper function
f <- function(x) {
  y <- diff(x)
  if (.indexmon(y)[1] == 0)
    y[1] <- x[1]
  y
}
# apply the function to each year subset and rbind the results
do.call(rbind, lapply(split(x,'years'), f))

Here's another way, that you might find more appealing.

colnames(x) <- "level"
# calculate all differences
x$diff <- diff(x$level)
# set January differences to their respective level
jan <- .indexmon(x) == 0
x[jan, "diff"] <- x[jan, "level"]


来源:https://stackoverflow.com/questions/29673985/error-with-xtsapply-error-in-coredata-xtsx-currently-unsupported-data-ty

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!