R中的步骤()如何处理交互和分类变量?
我在R中的步骤()如何处理交互和分类变量?,r,regression,lm,R,Regression,Lm,我在R中拟合了具有多重交互作用的线性回归lm 现在,我想做变量选择。为此,我打算使用步骤-功能 但是,我不确定step如何处理交互。我希望选择过程具有以下层次结构: 如果相互作用u:v保持不变,那么u和v本身也保持不变 对于虚拟变量x1和x2,如果x1保持不变,则x2也保持不变,反之亦然 我如何确保这一点?它已经以这种方式实现了吗?您可以使用regsubsets通过逐步回归获得所有可能的模型,并从满足您需求的模型中选取一个子集。例如,当只考虑双向交互时,您可以使用以下方法来满足第一个需求:
R
中拟合了具有多重交互作用的线性回归lm
现在,我想做变量选择。为此,我打算使用步骤
-功能
但是,我不确定step
如何处理交互。我希望选择过程具有以下层次结构:
- 如果相互作用u:v保持不变,那么u和v本身也保持不变
- 对于虚拟变量x1和x2,如果x1保持不变,则x2也保持不变,反之亦然
我如何确保这一点?它已经以这种方式实现了吗?您可以使用
regsubsets
通过逐步回归获得所有可能的模型,并从满足您需求的模型中选取一个子集。例如,当只考虑双向交互时,您可以使用以下方法来满足第一个需求:
require(leaps)
require(stringr)
tmp <- regsubsets(mpg ~ (wt + drat + disp + qsec)*(wt + drat + disp + qsec), data=mtcars, nbest=1000, really.big=T, intercept=T)
df <- summary(tmp)[[1]]
df <- as.data.frame(sapply(as.data.frame(df), as.numeric))
#for all columns in df which have ':' in the name, that is an interaction column
#if such a column is 1, each of the component columns must also be 1
comb_cols <- grep(":", names(df), value = TRUE)
for (i in 1:length(comb_cols)) {
this_comb <- comb_cols[i]
left_comp <- str_sub(this_comb, start = 1, end = str_locate(this_comb, ":")[1]-1)
right_comp <- str_sub(this_comb, start = str_locate(this_comb, ":")[1]+1, end = nchar(this_comb))
df[,left_comp] <- ifelse(df[,this_comb]==1, 1, df[,left_comp])
df[,right_comp] <- ifelse(df[,this_comb]==1, 1, df[,right_comp])
}
df <- df[!duplicated(df),]
require(跳跃)
要求(stringr)
tmp请看我的答案是否有用。是的,谢谢,我刚刚看到了