簡體   English   中英

使用 purrr::map2 具有所有變量排列的模型

[英]Models with all variable permutations using purrr::map2

以下代碼為我提供了模型a <- cb <- d ,但我想知道如何修改它以使其也具有a <- db <- c

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

假設哪些變量將是自變量或因變量是固定的。 在這種情況下, ab將是因變量, cd將是自變量。

你可以試試

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  

為此,您不需要 for 循環甚至 map。 只需重塑您的數據並為整個數據集做一個 lm。 檢查以下示例:

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

現在運行所有模型:

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   

結果如下:

前兩行是截距,后兩行是 B1 系數。 相比:

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  

現在您可以將其與Petal.Width進行比較

我想出了這個:

map(packs, library, character.only = TRUE) 

df <- tibble(a = 1:100, b = a^3, c = b/33, d = a/3) 
outcomes <- df %>%
   select(a, b)
predictors <- df %>%
   select(c, d)
map(outcomes, function(x) map(predictors, function(y) lm(x ~ y)))```

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM