Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting regression coefficients for all list elements without using a loop

Tags:

r

regression

Given two lists with identical keys, can you get regression coefficients into a third list without using loops and hopefully also without creating temporary data frames for each list item?

I'm familiar with lapply, but don't know how to apply it for this case, if that's even possible!

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
}
like image 800
forthrin Avatar asked Dec 05 '25 03:12

forthrin


1 Answers

Map the indicated anonymous function over x and y extracting the coefficients and concatenate that to the input s. No packages are used.

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

giving:

> 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"
like image 57
G. Grothendieck Avatar answered Dec 07 '25 17:12

G. Grothendieck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!