不使用循环获取所有列表元素的回归系数

Getting regression coefficients for all list elements without using a loop

给定两个具有相同键的列表,你能否在不使用循环的情况下将回归系数放入第三个列表中并且希望不为每个列表项创建临时数据框

我熟悉 lapply,但不知道如何将其应用到这种情况下,如果可能的话!

s = list()
s$x = list(a=c(1, 2, 3), b=c(4, 5, 6))
s$y = list(a=c(1, 2, 4), b=c(4, 5, 8))

for(i in names(s$x)) {
  df = data.frame(x = s$x[[i]], y = s$y[[i]])
  model = lm(y ~ x, df)
  s$co[[i]] = model$coefficients
}

也许这会有用

library(reshape2)
library(data.table)
setDT(melt(s))[, coef(lm(value[L1=="y"]~value[L1=="x"])) , L2]

或使用tidyverse

library(tidyverse)
s %>%
   transpose %>%
   map(~coef(lm(.[["y"]] ~ .[["x"]]))) %>%
   c(s, co = .)

或者,使用 lapply()base r

s = list()
s$x = list(a=c(1, 2, 3), b=c(4, 5, 6))
s$y = list(a=c(1, 2, 4), b=c(4, 5, 8))

coeff.list <- lapply(names(s$x), (function(i){
  df = data.frame(x = s$x[[i]], y = s$y[[i]])
  model = lm(y ~ x, df)
  model$coefficients
}))
names(coeff.list) <- names(s$x)

coeff.list

一个衬里解决方案

library(purrr)
s1 <- c(s, map2(s$x, s$y, ~lm(.y ~ .x)$co))

将指示的匿名函数映射到 x 和 y 上,提取系数并将其连接到输入 s。没有使用包。

s_out <- c(s, co = list(Map(function(x, y) coef(lm(y ~ x)), s$x, s$y)))

给予:

> str(s_out)
List of 3
 $ x :List of 2
  ..$ a: num [1:3] 1 2 3
  ..$ b: num [1:3] 4 5 6
 $ y :List of 2
  ..$ a: num [1:3] 1 2 4
  ..$ b: num [1:3] 4 5 8
 $ co:List of 2
  ..$ a: Named num [1:2] -0.667 1.5
  .. ..- attr(*, "names")= chr [1:2] "(Intercept)" "x"
  ..$ b: Named num [1:2] -4.33 2
  .. ..- attr(*, "names")= chr [1:2] "(Intercept)" "x"