Filling a list with lm objects

I am trying to populate a named list with OLS results in R. I tried

li = list() for (i in 1:10) li[["RunOne"]][i] = lm(y~x) 

Here RunOne is a random name that indicates a suitable run, y and x are some predefined vectors. It breaks and gives me an error

 Warning message: In l[["RunOne"]][1] = lm(y ~ x) : number of items to replace is not a multiple of replacement length 

Although I understand the error, I don’t know how to fix it.

+4
source share
1 answer

There are two solutions (depending on what you want to do).

  • Create a list and add an lm object to each element:

     li = list() for (i in 1:10) li[[i]] = lm(y~x) 
  • List of Lists:

     li[["RunOne"]] = list() for (i in 1:10) li[["RunOne"]][[i]] = lm(y~x) 

Typically, single brackets [ ] are used for vectors and frames, double brackets are used for lists.

+5
source

Source: https://habr.com/ru/post/1446818/


All Articles