Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Populating a list with lm objects

Tags:

list

for-loop

r

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

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

Here RunOne is a random name that designates the fitting run one, y and x are some predefined vectors. This breaks and gives me the error

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

Though I understand the error, but I don't know how to fix it.

like image 720
ganesh reddy Avatar asked Nov 18 '12 21:11

ganesh reddy


1 Answers

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

  1. Create a list, and add an lm object to each element:

    li = list() 
    for (i in 1:10) 
        li[[i]] = lm(y~x)
    
  2. Have a 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 data frames, double brackets are used for lists.

like image 181
csgillespie Avatar answered Oct 17 '22 04:10

csgillespie