mina
mina

Reputation: 195

how to get all objects of the same class in a list in R

I have implemented a linear regression on multiple dataframes. Now I want to create a list that will contain all my objects of class lm to later use them for other analysis.

My lmobjects are differentiated by groups according a name thus:

names(sortierfe)
[1] "bio1_lm"   "bio2_lm" "bio3_lm"   "chem1_lm" "chem2_lm" "chem3_lm" "pest1_lm"
[8] "pest2_lm" "pest3_lm"

I want to get 3 different list according to the names of the group like this:

bio.lm <- list(bio1_lm = bio1_lm, bio2_lm = bio2, bio3_lm = bio3=lm)
chem.lm <- list(chem1_lm = chem1_lm, chem2_lm = chem2_lm, chem3_lm = chem3_lm)
pest.lm <- list(pest1_lm = pest1_lm,pest2_lm = pest2_lm, pest3_lm = pest3_lm)     

Since I have 60 lmobjects this is a hard job to do manually, does any one know how can I optimize this?

Upvotes: 0

Views: 337

Answers (1)

akrun
akrun

Reputation: 887571

If we need to split, we can create a grouping index with sub. On the list output, we can get the values with mget

lst <- split(sortierfe, sub('\\d+\\_.*', '', sortierfe))
lapply(lst, mget)

Upvotes: 1

Related Questions