我在这里有一个R问题
我们经常做'正常'lm
:
model <- lm(y~0+x1+x2+x3, data=d)
但是,我要做的是在R脚本中动态选择x1
,x2
,x3
的名称。根据我适合的y
,函数可以以
model<-lm(y2~0+x10+x21+x33, data=d)
model<-lm(y3~0+x41+x15+x8, data=d)
等。请注意,从列表中依次选择y2
,y3
....实际上有一个功能
factorOfInterest <-getFactors(y)
任何人都知道如何编写这样的R脚本?或者,有没有更好的方法来构建问题?
答案 0 :(得分:0)
假设您的数据如下:
set.seed(1)
df1 <- data.frame(x1=rnorm(5),
x2=rnorm(5),
x3=rnorm(5),
y1=rnorm(5),
y2=rnorm(5)
)
以下内容将详细介绍x
s的所有组合,共7条:
### get columns named x
c1 <- colnames(df1)[grepl("x",colnames(df1))]
### make matrix of all combinations
library(combinat)
c2 <- combinat::hcube(rep(2, length(c1)))-1
### remove top row (represents intercept-only model)
c2 <- c2[-1, ]
### list to store results
l1 <- as.list(vector(length=nrow(c2)))
### use matrix for y values when fitting models
lhs1 <- cbind(df1$y1, df1$y2)
for (i in 1:nrow(c2)){
### subset of x variables
rhs1 <- c1[as.logical(c2[i, ])]
rhs1 <- paste0(rhs1, collapse="+")
f1 <- paste("lhs1", rhs1, sep="~")
f1 <- as.formula(f1)
l1[[i]] <- lm(f1)
}
(我确信更快的方法适用于较大的套装)......