【发布时间】:2019-03-16 22:35:00
【问题描述】:
给定一个数据集在一列中有多个唯一元素,我想将这些唯一元素拆分为新的数据框,但让数据框向下嵌套一层。本质上为split() 命令添加了一个额外的级别。
例如(以内置的iris 表为例:
iris
mylist <- split(iris, iris$Species)
产生一个列表mylist,其中包含3个子列表setosa、versicolor、virginica。
mylist[["setosa"]]
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1 5.1 3.5 1.4 0.2 setosa
2 4.9 3.0 1.4 0.2 setosa
3 4.7 3.2 1.3 0.2 setosa
4 4.6 3.1 1.5 0.2 setosa
5 5.0 3.6 1.4 0.2 setosa
但我实际上想将该数据表嵌套在名为results 的子列表中,但将上层列表名称保留为setosa。这样:
mylist$setosa["results"]
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1 5.1 3.5 1.4 0.2 setosa
2 4.9 3.0 1.4 0.2 setosa
3 4.7 3.2 1.3 0.2 setosa
4 4.6 3.1 1.5 0.2 setosa
5 5.0 3.6 1.4 0.2 setosa
我可以通过手动操作来做到这一点,但我希望它自动运行。我用mapply尝试失败了
mapply(function(names, df)
names <- split(df, df[["Species"]]),
unique(iris$Species), iris)
有什么建议吗?如果这能让事情变得更容易,也很高兴使用tidyr 包......
【问题讨论】:
-
dplyr::group_by(iris, Species) %>% tidyr::nest() %>% %>% { set_names(.$data, .$Species) };split(iris, iris$Species) %>% as.list()
标签: r list nested lapply mapply