Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/74.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 向线性模型中添加交互项序列,lm()_R_Dplyr_Tidyverse_Lm - Fatal编程技术网

R 向线性模型中添加交互项序列,lm()

R 向线性模型中添加交互项序列,lm(),r,dplyr,tidyverse,lm,R,Dplyr,Tidyverse,Lm,我的数据格式如下: mpg disp c1 c2 c3 21.0 160.0 0 0 0 21.0 160.0 0 0 0 22.8 108.0 1 0 0 21.4 258.0 1 0 0 18.7 360.0 0 1 0 18.1 225.0 1 0 0 我想运行这样一个线性模型,c1到c3都与另一个解释变量disp相互作用: lm(mpg ~ disp:c1

我的数据格式如下:

mpg     disp    c1  c2  c3
21.0    160.0   0   0   0
21.0    160.0   0   0   0
22.8    108.0   1   0   0
21.4    258.0   1   0   0
18.7    360.0   0   1   0
18.1    225.0   1   0   0
我想运行这样一个线性模型,
c1
c3
都与另一个解释变量
disp
相互作用:

lm(mpg ~ disp:c1 
       + disp:c2
       + disp:c3, df)
当然,我的真实数据集有3个以上的交互,但是我需要交互的所有变量都是按列顺序排列的,并且都是按顺序命名的(例如c1、c2等)

有没有一种简单的方法来指定
disp
c1
之间的交互,比如说
c100

下面是复制示例数据集的代码:

library(dplyr)
df <- mtcars
df <- df %>% mutate(c = factor(carb))
dummies <- model.matrix(data = df, ~ c + 0)
dummies <- as_data_frame(dummies)
df <- cbind(df, dummies)
df <- df %>% select(mpg, disp, c1:c3)
head(df)
库(dplyr)

df
按要求顺序粘贴
值,并使用公式

lm(formula(paste0("mpg ~ ", paste0("disp:", "c", 1:3, collapse = " + "))), df)

#Call:
#lm(formula = formula(paste0("mpg ~ ", paste0("disp:", "c", 1:3, 
#    collapse = " + "))), data = df)

#Coefficients:
#(Intercept)      disp:c1      disp:c2      disp:c3  
# 19.7862454    0.0196435    0.0008339   -0.0126405 
在哪里

paste0("mpg ~ ", paste0("disp:", "c", 1:3, collapse = " + ")) #gives
#[1] "mpg ~ disp:c1 + disp:c2 + disp:c3"
手动应用功能
lm

lm(mpg ~ disp:c1 + disp:c2 + disp:c3, df)

我们可以使用
重新格式化

lm(reformulate(paste0("disp:", "c", 1:3), "mpg"), df)
#Call:
#lm(formula = reformulate(paste0("disp:", "c", 1:3), "mpg"), data = df)

#Coefficients:
#(Intercept)      disp:c1      disp:c2      disp:c3  
# 19.7862454    0.0196435    0.0008339   -0.0126405