I have a data table as follows:
## install.packages(c("gapminder", "data.table"))
library(gapminder)
library(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 from this data table that mdlshould lie inside each countryone that is itself embedded in continent.
I tried to get the result like,
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 an elegant way to do this?
source
share