我有一个data.table如下,
## 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)]
结果表将是,
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>
现在我想从这个data.table中获取一个列表,这样mdl应该位于每个国家内,而这个国家本身就嵌套在大陆内.
我试图得到结果,
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))
有没有优雅的方法来做到这一点?
最佳答案 您可以使用此类代码获取要查找的嵌套列表:
res<-lapply(unique(my_table$continent),
function(x){lapply(unique(my_table[continent==x]$country),
function(z){my_table[continent==x&country==z]})})