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

标签 r loops 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

但是,我想更进一步,并使用 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/

相关文章:

R 命令 dir.create 和 file.path

excel - 计算机因简单代码而窒息。我错过了什么?

javascript - 从多维数组中提取值

r - 组合错误 : Error in FUN(X[[i]], ...) 的含义:R 中的 n < m

r - 从具有重复元素的向量生成所有唯一组合

r - 如何让 Shiny-server 使用 Azure Active Directory

r - R 中的 Monte Carlo 模拟、Bootstrap 和回归

python - 当每个循环读取上一个循环的结果时优化Python循环

r - 有效地找到R中两个时间间隔之间的重叠

r 中数据帧中每列的最后 12 行的滚动总和