我有以下随机相关系列向量。 (包quantmod)
x <- filter(rnorm(100), filter=rep(1,3), circular=TRUE)
#I run the autocorrelation and confidence intervals
a <- acf(x)
b <- a[[1]]
c <- (b[2:length(b)])
posssignificance_level <- qnorm((1+0.95)/2)/sqrt(sum(!is.na(x)))
negsignificance_level <- -posssignificance_level
#obtaining the frequency of the autocorrelation
poscorr <- which(posssignificance_level<c)
negcorr <- which(negsignificance_level>c)
#lag the initial series by the different autocorrelation frequencies
posautorrelation <- if(length(poscorr) == 0) Lag(as.numeric(x),0) else
na.omit(posautorrelation <- Lag(as.numeric(x), poscorr))
negautorrelation <- if(length(negcorr) == 0) Lag(as.numeric(x),0) else
na.omit(negautorrelation <- Lag(as.numeric(x), negcorr))
#Then I make equal the starting point for each column obtained by
shortest <- min((length(posautorrelation))/(length(poscorr)),
(length(negautorrelation))/(length(negcorr)))
posautorrelation <- tail(posautorrelation, shortest)
negautorrelation <- tail(negautorrelation, shortest)
tpos <- na.omit(posautorrelation); rownames(tpos)<-NULL
tneg <- na.omit(negautorrelation); rownames(tneg)<-NULL
#Producing a dataframe with colnames similar to Lag.4...
c <- data.frame(tpos,tneg)
#Adjusting the length of x to the minimum lag
correction <- length(x)-length(tpos[,1])
z <- x[(correction+1):length(x)]
z <- c(z,0)
当我将数据框c粘贴到下面的表达式中时,我在Lag.4列中获得了数字的向量,并且类似。做粘贴(colnames(c)..产生列的鬃毛,当最后将pastevar应用到模型矩阵时,我得到一个错误,告诉我无法找到对象Lag.4 ... .tposs和tneg拥有每个多列,并且可能试图通过仅列出tpos和tneg将这些多列放在data.frame中可能不是正确的方法。
pastevar <- paste(c("z[2:length(z)] ~ ", paste(c, collapse=" + ")))
X <- model.matrix(as.formula(pastevar))[,-1]
通过粘贴函数传递数据框的正确方法是什么,以便获取data.frame的每一列?
答案 0 :(得分:1)
我想你正在寻找以下代码:
# You want 'names(c)' instead of 'c'
# and don't need the 'c' function
pastevar <- paste("z[2:length(z)] ~ ", paste(names(c), collapse=" + "))
# [1] "z[2:length(z)] ~ Lag.1 + Lag.2 + Lag.15 + Lag.16"
# You need to pass a data frame to the function 'model.matrix'
X <- model.matrix(as.formula(pastevar), c)[,-1]
# Lag.1 Lag.2 Lag.15 Lag.16
# 1 -0.74870676 0.01337777 0.96744542 0.17647578
# 2 -2.97027457 -0.74870676 1.61315456 0.96744542
# 3 -3.82279738 -2.97027457 0.53727069 1.61315456
# 4 -3.47817458 -3.82279738 1.54034858 0.53727069
# 5 -2.26750524 -3.47817458 2.26544218 1.54034858
# 6 -1.17946841 -2.26750524 2.64224392 2.26544218
# ...
顺便说一句:c
不是数据框的好名字,因为它也是一个非常基本的函数的名称。