gpt4 book ai didi

r - 使用 split() 嵌套多个列表,R

转载 作者:行者123 更新时间:2023-12-01 23:03:25 30 4
gpt4 key购买 nike

给定一个数据集在一列中有多个唯一元素,我想将这些唯一元素拆分为新的数据框,但让数据框向下嵌套一层。本质上为 split() 命令添加了一个额外的级别。

例如(以内置的iris表为例:

iris
mylist <- split(iris, iris$Species)

产生一个列表 mylist,其中包含 3 个子列表 setosaversicolorvirginica

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 包......

最佳答案

考虑 by(tapply 的面向对象的包装器),与 split 非常相似,但允许您在每个子集上运行一个函数。很多用户经常运行 split + lapply,不知道两者都可以替换为 by:

mylist <- by(iris, iris$Species, function(sub) list(results=sub), simplify = FALSE)

head(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
# 6 5.4 3.9 1.7 0.4 setosa

head(mylist$versicolor$results)
# Sepal.Length Sepal.Width Petal.Length Petal.Width Species
# 51 7.0 3.2 4.7 1.4 versicolor
# 52 6.4 3.2 4.5 1.5 versicolor
# 53 6.9 3.1 4.9 1.5 versicolor
# 54 5.5 2.3 4.0 1.3 versicolor
# 55 6.5 2.8 4.6 1.5 versicolor
# 56 5.7 2.8 4.5 1.3 versicolor

head(mylist$virginica$results)
# Sepal.Length Sepal.Width Petal.Length Petal.Width Species
# 101 6.3 3.3 6.0 2.5 virginica
# 102 5.8 2.7 5.1 1.9 virginica
# 103 7.1 3.0 5.9 2.1 virginica
# 104 6.3 2.9 5.6 1.8 virginica
# 105 6.5 3.0 5.8 2.2 virginica
# 106 7.6 3.0 6.6 2.1 virginica

关于r - 使用 split() 嵌套多个列表,R,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52766920/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com