data.table in the nested list


I have a data.table as follows,

## install.packages(c("gapminder", "data.table"))
gapminder <- data.table(gapminder)
my_table <- gapminder[, .(mdl = .(lm(lifeExp ~ pop + gdpPercap,
                                  data = gapminder))),
                          by = .(country, continent)]

The resulting table will be,

                country continent  mdl
  1:        Afghanistan      Asia <lm>
  2:            Albania    Europe <lm>
  3:            Algeria    Africa <lm>
  4:             Angola    Africa <lm>
  5:          Argentina  Americas <lm>
138:            Vietnam      Asia <lm>
139: West Bank and Gaza      Asia <lm>
140:        Yemen, Rep.      Asia <lm>
141:             Zambia    Africa <lm>
142:           Zimbabwe    Africa <lm>

Now I want to get a list out of this data.table such that mdl should lie within each country which itself is nested within continent.

I have tried to get the result as,

first_list <- split(my_table, my_table$continent)
second_list <- lapply(first_list, function(x){
                   split(x[, country := as.character(country)], x$country)
final_list <- sapply(second_list, function(x) sapply(x, function(y) y$mdl))

Is there any elegant way to do this?

You can have the nested list you are looking for with this kind of code :