gpt4 book ai didi

r - 访问 dplyr 中的分组数据

转载 作者:行者123 更新时间:2023-12-04 03:27:35 24 4
gpt4 key购买 nike

从 dplyr 应用 group_by 函数并使用 %.% 运算符后,如何访问分组数据

例如,如果我想拥有每个分组数据的第一行,那么我可以使用 plyr 包作为

ddply(iris,.(Species),function(df){
df[1,]
})

#output
# Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#1 5.1 3.5 1.4 0.2 setosa
#2 7.0 3.2 4.7 1.4 versicolor
#3 6.3 3.3 6.0 2.5 virginica

最佳答案

对于您的具体情况,您可以使用 row_number() :

library(dplyr)

iris %.%
group_by(Species) %.%
filter(row_number(Species) == 1)
## Source: local data frame [3 x 5]
## Groups: Species
##
## Sepal.Length Sepal.Width Petal.Length Petal.Width Species
## 1 5.1 3.5 1.4 0.2 setosa
## 2 7.0 3.2 4.7 1.4 versicolor
## 3 6.3 3.3 6.0 2.5 virginica

这在 0.2 版中会更自然一些,因为您可以省略
变量的名称:
# devtools::install_github("hadley/dplyr")

iris %.%
group_by(Species) %.%
filter(row_number() == 1)
## Source: local data frame [3 x 5]
## Groups: Species
##
## Sepal.Length Sepal.Width Petal.Length Petal.Width Species
## 1 5.1 3.5 1.4 0.2 setosa
## 2 7.0 3.2 4.7 1.4 versicolor
## 3 6.3 3.3 6.0 2.5 virginica

对于任意操作, do()在 0.2 中更有用。你给它
任意表达式,使用 .作为每个组的占位符:
iris %.% 
group_by(Species) %.%
do(.[1, ])
## Source: local data frame [3 x 6]
## Groups: Species
##
## Species Sepal.Length Sepal.Width Petal.Length Petal.Width Species.1
## 1 setosa 5.1 3.5 1.4 0.2 setosa
## 2 versicolor 7.0 3.2 4.7 1.4 versicolor
## 3 virginica 6.3 3.3 6.0 2.5 virginica

关于r - 访问 dplyr 中的分组数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22709206/

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