数据框中变量的回归 [英] Regression of variables in a dataframe
问题描述
我有一个数据框:
df = data.frame(x1 = rnorm(50), x2 = rnorm(50), x3 = rnorm(50), x4 = rnorm(50))
我想将每个变量与所有其他变量进行回归,例如:
I would like to regress each variable versus all the other variables, for instance:
fit1 <- lm(x1 ~ ., data = df)
fit2 <- lm(x2 ~ ., data = df)
等(当然,实际的数据框具有更多的变量).
etc. (Of course, the real dataframe has a lot more variables).
我尝试将它们放在一个循环中,但是没有用.我也尝试使用 lapply
,但也无法产生所需的结果.有人知道这个窍门吗?
I tried putting them in a loop, but it didn't work. I also tried using lapply
but couldn't produce the desired result either. Does anyone know the trick?
推荐答案
您可以使用 reformulate
动态构建正式版
You can use reformulate
to dynamically build formuals
df = data.frame(x1 = rnorm(50), x2 = rnorm(50), x3 = rnorm(50), x4 = rnorm(50))
vars <- names(df)
result <- lapply(vars, function(resp) {
lm(reformulate(".",resp), data=df)
})
或者,您可以使用do.call在每个模型中获取更漂亮"的公式
alternatively you could use do.call to get "prettier" formauls in each of the models
vars <- names(df)
result <- lapply(vars, function(resp) {
do.call("lm", list(reformulate(".",resp), data=quote(df)))
})
这些方法中的每一个都返回一个列表.您可以使用 result [[1]]
, result [[2]]
等
each of these methods returns a list. You can extract individual models with result[[1]]
, result[[2]]
, etc
这篇关于数据框中变量的回归的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!