R:如何从数据集的组合中执行更复杂的计算?

Luk*_*ang 6 loops r combn

现在,我有一个来自内置数据集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
Run Code Online (Sandbox Code Playgroud)

但是,我想进一步使用lm()中的系数来进一步计算.我想做这样的事情:

Coefficient <- lm(formula=x, data=iris)$coefficients[2]
Spread <- myPairs[1] - coefficient*myPairs[2]
library(tseries)
adf.test(Spread)
Run Code Online (Sandbox Code Playgroud)

该过程本身很简单,但我还没有找到一种方法来为数据集中的每个组合执行此操作.(作为旁注,adf.test不适用于此类数据,但我只是使用虹膜数据集进行演示).我想知道,为这样的程序编写一个循环会更好吗?

use*_*650 2

您可以在 内完成所有这些操作combn

如果您只想对所有组合运行回归,并提取第二个系数,您可以这样做

fun <- function(x) coef(lm(paste(x, collapse="~"), data=iris))[2]
combn(names(iris[1:4]), 2, fun)
Run Code Online (Sandbox Code Playgroud)

然后您可以扩展该函数来计算点差

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
Run Code Online (Sandbox Code Playgroud)

将结果与手动运行第一个结果进行比较

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
Run Code Online (Sandbox Code Playgroud)