从分组数据中选择第一行和最后一行


137

使用dplyr,如何在一个语句中选择分组数据的顶部和底部观察/行?

数据与示例

给定数据框

df <- data.frame(id=c(1,1,1,2,2,2,3,3,3), 
                 stopId=c("a","b","c","a","b","c","a","b","c"), 
                 stopSequence=c(1,2,3,3,1,4,3,1,2))

我可以使用slice,但使用两个单独的语句从每个组中获得最高和最低观察值:

firstStop <- df %>%
  group_by(id) %>%
  arrange(stopSequence) %>%
  slice(1) %>%
  ungroup

lastStop <- df %>%
  group_by(id) %>%
  arrange(stopSequence) %>%
  slice(n()) %>%
  ungroup

我可以将这两个statmenets合并成一个选择两个顶部和底部的意见?


Answers:


232

可能有一种更快的方法:

df %>%
  group_by(id) %>%
  arrange(stopSequence) %>%
  filter(row_number()==1 | row_number()==n())

66
rownumber() %in% c(1, n())将消除两次运行矢量扫描的需要
MichaelChirico

13
@MichaelChirico我怀疑你省略了_吗?即filter(row_number() %in% c(1, n()))
埃里克失败

107

仅出于完整性考虑:您可以传递slice索引向量:

df %>% arrange(stopSequence) %>% group_by(id) %>% slice(c(1,n()))

这使

  id stopId stopSequence
1  1      a            1
2  1      c            3
3  2      b            1
4  2      c            4
5  3      b            1
6  3      a            3

甚至可能会快于filter-没有测试过这一点,但看到这里
Tjebo

1
@Tjebo与filter不同,slice可以多次返回同一行,例如,mtcars[1, ] %>% slice(c(1, n()))因此在这种情况下,它们之间的选择取决于您要返回的内容。我希望除非n有很大的时间(可能更喜欢切片),否则时间会很近,但是也没有进行测试。
弗兰克,

15

不是dplyr,但是使用data.table以下命令更直接:

library(data.table)
setDT(df)
df[ df[order(id, stopSequence), .I[c(1L,.N)], by=id]$V1 ]
#    id stopId stopSequence
# 1:  1      a            1
# 2:  1      c            3
# 3:  2      b            1
# 4:  2      c            4
# 5:  3      b            1
# 6:  3      a            3

更详细的解释:

# 1) get row numbers of first/last observations from each group
#    * basically, we sort the table by id/stopSequence, then,
#      grouping by id, name the row numbers of the first/last
#      observations for each id; since this operation produces
#      a data.table
#    * .I is data.table shorthand for the row number
#    * here, to be maximally explicit, I've named the variable V1
#      as row_num to give other readers of my code a clearer
#      understanding of what operation is producing what variable
first_last = df[order(id, stopSequence), .(row_num = .I[c(1L,.N)]), by=id]
idx = first_last$row_num

# 2) extract rows by number
df[idx]

请务必查看“ 入门”维基,以data.table了解基础知识


1
或者df[ df[order(stopSequence), .I[c(1,.N)], keyby=id]$V1 ]。看到id出现两次对我来说很奇怪。
2015年

您可以在setDT通话中设置按键。因此,order这里不需要通话。
Artem Klevtsov '17

1
@ArtemKlevtsov-但是,您可能并不总是想要设置按键。
SymbolixAU

2
或者df[order(stopSequence), .SD[c(1L,.N)], by = id]。看到这里
JWilliman '17

@JWilliman不一定完全相同,因为它不会在上重新排序id。我认为df[order(stopSequence), .SD[c(1L, .N)], keyby = id]应该做到这一点(与上述解决方案的细微差异将使结果得到key编辑
-MichaelChirico

8

就像是:

library(dplyr)

df <- data.frame(id=c(1,1,1,2,2,2,3,3,3),
                 stopId=c("a","b","c","a","b","c","a","b","c"),
                 stopSequence=c(1,2,3,3,1,4,3,1,2))

first_last <- function(x) {
  bind_rows(slice(x, 1), slice(x, n()))
}

df %>%
  group_by(id) %>%
  arrange(stopSequence) %>%
  do(first_last(.)) %>%
  ungroup

## Source: local data frame [6 x 3]
## 
##   id stopId stopSequence
## 1  1      a            1
## 2  1      c            3
## 3  2      b            1
## 4  2      c            4
## 5  3      b            1
## 6  3      a            3

随着do你几乎可以在组执行任何数量的操作,但@ jeremycg的答案是方式更适用于只是这个任务。


1
没有考虑编写函数-当然是做更复杂事情的好方法。
tospig

1
与仅使用相比,这似乎过于复杂了slice,例如df %>% arrange(stopSequence) %>% group_by(id) %>% slice(c(1,n()))
Frank

4
没有不同意(我指着jeremycg作为一个更好的答案后),但有一个do在这里的例子可能帮助别人的时候slice将无法正常工作(即一组更复杂的操作)。而且,您可以发表评论作为答案(这是最好的答案)。
hrbrmstr

6

我知道指定的问题dplyr。但是,由于其他人已经发布了使用其他软件包的解决方案,因此我决定也可以使用其他软件包:

基本包装:

df <- df[with(df, order(id, stopSequence, stopId)), ]
merge(df[!duplicated(df$id), ], 
      df[!duplicated(df$id, fromLast = TRUE), ], 
      all = TRUE)

data.table:

df <-  setDT(df)
df[order(id, stopSequence)][, .SD[c(1,.N)], by=id]

sqldf:

library(sqldf)
min <- sqldf("SELECT id, stopId, min(stopSequence) AS StopSequence
      FROM df GROUP BY id 
      ORDER BY id, StopSequence, stopId")
max <- sqldf("SELECT id, stopId, max(stopSequence) AS StopSequence
      FROM df GROUP BY id 
      ORDER BY id, StopSequence, stopId")
sqldf("SELECT * FROM min
      UNION
      SELECT * FROM max")

在一个查询中:

sqldf("SELECT * 
        FROM (SELECT id, stopId, min(stopSequence) AS StopSequence
              FROM df GROUP BY id 
              ORDER BY id, StopSequence, stopId)
        UNION
        SELECT *
        FROM (SELECT id, stopId, max(stopSequence) AS StopSequence
              FROM df GROUP BY id 
              ORDER BY id, StopSequence, stopId)")

输出:

  id stopId StopSequence
1  1      a            1
2  1      c            3
3  2      b            1
4  2      c            4
5  3      a            3
6  3      b            1

3

使用which.minwhich.max

library(dplyr, warn.conflicts = F)
df %>% 
  group_by(id) %>% 
  slice(c(which.min(stopSequence), which.max(stopSequence)))

#> # A tibble: 6 x 3
#> # Groups:   id [3]
#>      id stopId stopSequence
#>   <dbl> <fct>         <dbl>
#> 1     1 a                 1
#> 2     1 c                 3
#> 3     2 b                 1
#> 4     2 c                 4
#> 5     3 b                 1
#> 6     3 a                 3

基准

它也比当前接受的答案快得多,因为我们按组查找最小值和最大值,而不是对整个stopSequence列进行排序。

# create a 100k times longer data frame
df2 <- bind_rows(replicate(1e5, df, F)) 
bench::mark(
  mm =df2 %>% 
    group_by(id) %>% 
    slice(c(which.min(stopSequence), which.max(stopSequence))),
  jeremy = df2 %>%
    group_by(id) %>%
    arrange(stopSequence) %>%
    filter(row_number()==1 | row_number()==n()))
#> Warning: Some expressions had a GC in every iteration; so filtering is disabled.
#> # A tibble: 2 x 6
#>   expression      min   median `itr/sec` mem_alloc `gc/sec`
#>   <bch:expr> <bch:tm> <bch:tm>     <dbl> <bch:byt>    <dbl>
#> 1 mm           22.6ms     27ms     34.9     14.2MB     21.3
#> 2 jeremy      254.3ms    273ms      3.66    58.4MB     11.0

2

使用data.table

# convert to data.table
setDT(df) 
# order, group, filter
df[order(stopSequence)][, .SD[c(1, .N)], by = id]

   id stopId stopSequence
1:  1      a            1
2:  1      c            3
3:  2      b            1
4:  2      c            4
5:  3      b            1
6:  3      a            3

1

lapply和dplyr语句的另一种方法。我们可以将任意数量的摘要功能应用于同一条语句:

lapply(c(first, last), 
       function(x) df %>% group_by(id) %>% summarize_all(funs(x))) %>% 
bind_rows()

例如,您可能也对具有最大stopSequence值的行感兴趣,然后执行以下操作:

lapply(c(first, last, max("stopSequence")), 
       function(x) df %>% group_by(id) %>% summarize_all(funs(x))) %>%
bind_rows()

0

一个不同的基R替代方案是首先order使用idstopSequencesplit它们基于id,对于每一个,id我们仅选择第一个和最后一个索引,并使用这些索引对数据帧进行子集化。

df[sapply(with(df, split(order(id, stopSequence), id)), function(x) 
                   c(x[1], x[length(x)])), ]


#  id stopId stopSequence
#1  1      a            1
#3  1      c            3
#5  2      b            1
#6  2      c            4
#8  3      b            1
#7  3      a            3

或类似使用 by

df[unlist(with(df, by(order(id, stopSequence), id, function(x) 
                   c(x[1], x[length(x)])))), ]
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.