【问题标题】:Accessing grouped data in dplyr访问 dplyr 中的分组数据
【发布时间】:2014-05-07 16:49:18
【问题描述】:

从 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  

【问题讨论】:

  • 我并不完全清楚您所说的“访问组数据”是什么意思。你能详细说明一下吗?
  • 我想在使用 dplyr 包中的 group_by 函数并使用 %.% 后访问每个组
  • 您可以添加一个summarise(myfun = myfun(column)) 来处理块,其中 myfun 是一个可以处理块的自定义函数。如果您打开browser,您将能够看到正在处理的值。

标签: r plyr dplyr


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    我发现可能有帮助的唯一方法是使用 do 函数。

    library(dplyr)
    
    g.iris <- group_by(x=iris, Species)
    
    do(g.iris, function(x){ head(x, n=1)})
    

    【讨论】:

    • 如果与 %.% 运算符一起使用,则返回一个列表
    猜你喜欢
    • 1970-01-01
    • 2017-12-26
    • 1970-01-01
    • 2016-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多