本文介绍了在dplyr中访问分组数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I access the grouped data after applying group_by function from dplyr and using %.% operator

,我如何访问分组数据,例如,如果我想要分组数据,那么我可以使用plyr包作为

For example, If I want to have the first row of each grouped data then I can do this using plyr package as

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()

For your specific case, you can use 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版本中将会更加自然:

This will be a little more natural in version 0.2 since you can omit thevariable name:

# 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中更有用。您可以使用
任意表达式,使用作为每个组的占位符:

For arbitrary operations, do() is much more useful in 0.2. You give itarbitrary expressions, using . as a placeholder for each group:

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

这篇关于在dplyr中访问分组数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-24 14:09