Home > front end >  Models with all variable permutations using purrr::map2
Models with all variable permutations using purrr::map2

Time:12-01

The following code gives me models a <- c and b <- d, but I was wondering how I could modify it to also have a <- d and b <- c

outcomes <- df %>%
   select(a, b)
predictors <- df %>%
   select(c, d)
model <- function(outcomes, predictors) lm(outcomes ~ predictors)
map2(outcomes, predictors, model)``` 

CodePudding user response:

Suppose that which variables will be independent or dependent variables are fixed. In this case, a and b will be dependent variable and c and d will be independent variable.

You may try

df <- data.frame(
  a = 1:4,
  b = 2:5,
  c = rnorm(4),
  d = runif(4)
)
dep <- c("a", "b")
indep <- c("c", "d")

indep <- gtools::permutations(n = 2, r = 2, v = indep)

df %>%
  select(dep)

df %>%
  select(indep[1,])

modlist <- list()
for (i in 1:nrow(indep)){
  outcomes <- df %>%
    select(dep)
  predictors_ <- df %>%
    select(indep[i,])
  fit <- function(outcomes, predictors_) lm(outcomes ~ predictors_)
  modlist[[i]] <- map2(outcomes, predictors_, fit) 
}
modlist

[[1]]
[[1]]$a

Call:
lm(formula = outcomes ~ predictors_)

Coefficients:
(Intercept)  predictors_  
     2.4296      -0.2222  


[[1]]$b

Call:
lm(formula = outcomes ~ predictors_)

Coefficients:
(Intercept)  predictors_  
      2.058        2.631  



[[2]]
[[2]]$a

Call:
lm(formula = outcomes ~ predictors_)

Coefficients:
(Intercept)  predictors_  
      1.058        2.631  


[[2]]$b

Call:
lm(formula = outcomes ~ predictors_)

Coefficients:
(Intercept)  predictors_  
     3.4296      -0.2222  

CodePudding user response:

You do not need a for-loop or even map for this. Just reshape your data and do an lm for the whole dataset. Check example below:

data <- head(iris[-5], 6)
 
indep <- c('Sepal.Length',  'Petal.Length')
dep <- c('Sepal.Width',  'Petal.Width')

Now to run all the models:

data %>%
  pivot_longer(all_of(indep))%>%
  lm(as.matrix(.[dep])~0   name/value, .)

Call:
lm(formula = as.matrix(.[dep]) ~ 0   name/value, data = .)

Coefficients:
                        Sepal.Width  Petal.Width
namePetal.Length         1.1702      -0.5298    
nameSepal.Length        -1.6859      -0.8402    
namePetal.Length:value   1.5263       0.5263    
nameSepal.Length:value   1.0241       0.2169   

The results are as follows:

The first two rows are the intercepts and the last 2 rows are the B1 coefficients. compare:

lm(Sepal.Width~Petal.Length, data)

Call:
lm(formula = Sepal.Width ~ Petal.Length, data = data)

Coefficients:
 (Intercept)  Petal.Length  
       1.170         1.526  

lm(Sepal.Width~Sepal.Length, data)

Call:
lm(formula = Sepal.Width ~ Sepal.Length, data = data)

Coefficients:
 (Intercept)  Sepal.Length  
      -1.686         1.024  

Now you can compare the same with Petal.Width

  • Related