xts::apply出现错误:";coredata.xts(x)中出错:当前不支持的数据类型;

xts::apply出现错误:";coredata.xts(x)中出错:当前不支持的数据类型;,r,apply,xts,R,Apply,Xts,我在尝试执行以下工作时出错: # 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) 每年,y(t)=y(t-1)+dy,其中dt是t期间的值变化。但这种模式只在每年和每年分别发生。所以基本上,我想检索每个特定年份中每个月之间的差异,即: 1990-05 20 #100-80

我在尝试执行以下工作时出错:

# 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)
每年,
y(t)=y(t-1)+dy
,其中
dt
是t期间的值变化。但这种模式只在每年和每年分别发生。所以基本上,我想检索每个特定年份中每个月之间的差异,即:

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  
...
希望我已经解释清楚了


谢谢,

应用。每月
期间。应用
用于将数据聚合到指定期间
diff
不起作用,因为
diff.xts
返回与输入长度相同的向量
mean
之所以有效,是因为它为给定的输入向量返回一个值

我不清楚您希望每月(数据、差异)应用什么。这与调用
diff(data)
然后将
NA
添加到每个月的第一个值相同


通过你的编辑,我现在明白你想做什么了。您需要差异,但希望每年的1月是该月的级别,而不是与前一年12月的差异

这里有一种方法:

# 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))
#以加载数据为例

谢谢你的回答。这是很合理的。更详细的解释加上为什么我需要申请。每月(数据,差异)之类的东西。
# 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))
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"]