【问题标题】:Getting regression coefficients for all list elements without using a loop在不使用循环的情况下获取所有列表元素的回归系数
【发布时间】:2018-02-04 08:48:04
【问题描述】:

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

我熟悉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
}

【问题讨论】:

    标签: r regression


    【解决方案1】:

    将指定的匿名函数映射到 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"
    

    【讨论】:

    • 这是迄今为止我个人最喜欢的。它简短、易于阅读,并且不使用任何软件包。
    【解决方案2】:

    一个衬垫解决方案

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

    【讨论】:

      【解决方案3】:

      也许这会有用

      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 = .)
      

      【讨论】:

        【解决方案4】:

        或者,使用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
        

        【讨论】:

          猜你喜欢
          • 2020-04-07
          • 2020-11-08
          • 1970-01-01
          • 2022-12-11
          • 2021-10-09
          • 2020-02-26
          • 1970-01-01
          • 2016-04-20
          • 2011-12-19
          相关资源
          最近更新 更多