在dplyr中访问分组数据

时间:2014-03-28 09:48:11

标签: r plyr dplyr

如何在从dplyr应用group_by函数并使用%。%operator

后访问分组数据

例如,如果我想拥有每个分组数据的第一行,那么我可以使用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  

2 个答案:

答案 0 :(得分:13)

对于您的具体情况,您可以使用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

答案 1 :(得分:1)

我发现可能有用的唯一方法是使用do功能。

library(dplyr)

g.iris <- group_by(x=iris, Species)

do(g.iris, function(x){ head(x, n=1)})