现在,我有一个来自内置数据集 iris 的组合。到目前为止,我已经被引导到能够找到这对值的 lm() 系数。
myPairs <- combn(names(iris[1:4]), 2)
formula <- apply(myPairs, MARGIN=2, FUN=paste, collapse="~")
model <- lapply(formula, function(x) lm(formula=x, data=iris)$coefficients[2])
model
但是,我想更进一步,并使用 lm() 中的系数用于进一步计算。我想做这样的事情:
Coefficient <- lm(formula=x, data=iris)$coefficients[2]
Spread <- myPairs[1] - coefficient*myPairs[2]
library(tseries)
adf.test(Spread)
该过程本身很简单,但我一直无法找到一种方法来为数据集中的每个组合执行此操作。 (作为旁注,adf.test 不会应用于此类数据,但我只是使用 iris 数据集进行演示)。
我想知道,为这样的过程编写一个循环会更好吗?
最佳答案
您可以在 combn
内完成所有这些操作.
如果您只想对所有组合运行回归,并提取您可以执行的第二个系数
fun <- function(x) coef(lm(paste(x, collapse="~"), data=iris))[2]
combn(names(iris[1:4]), 2, fun)
然后您可以扩展该函数来计算点差
fun <- function(x) {
est <- coef(lm(paste(x, collapse="~"), data=iris))[2]
spread <- iris[,x[1]] - est*iris[,x[2]]
adf.test(spread)
}
out <- combn(names(iris[1:4]), 2, fun, simplify=FALSE)
out[[1]]
# Augmented Dickey-Fuller Test
#data: spread
#Dickey-Fuller = -3.879, Lag order = 5, p-value = 0.01707
#alternative hypothesis: stationary
将结果与手动运行第一个进行比较
est <- coef(lm(Sepal.Length ~ Sepal.Width, data=iris))[2]
spread <- iris[,"Sepal.Length"] - est*iris[,"Sepal.Width"]
adf.test(spread)
# Augmented Dickey-Fuller Test
# data: spread
# Dickey-Fuller = -3.879, Lag order = 5, p-value = 0.01707
# alternative hypothesis: stationary
关于R:如何从数据集的组合中执行更复杂的计算?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37841678/