簡體   English   中英

如何使用R和dplyr中連續的元素執行group_by

[英]How to perform a group_by with elements that are contiguous in R and dplyr

假設我們有這個小標題:

 group item
 x     1
 x     2
 x     2
 y     3
 z     2
 x     2
 x     2
 z     1

我想按組執行group_by。 但是,我只希望按相鄰的元素分組。 例如,在我的情況下,我將有三個“ x”組,將“ item”元素相加。 結果將是這樣的:

group item
x 5
y 3
z 2
x 4
z 1

我知道如何使用“ for”循環解決此問題。 但是,這並不快,聽起來也不是那么簡單。 我寧願使用帶有簡單邏輯的dplyr或tidyverse函數。

這個問題沒有重復。 我知道在SO中已經存在關於rle的問題,但是我的問題比這更籠統。 我要求一般解決方案。

如果您只想使用基本R + tidyverse,則此代碼可精確復制您想要的結果

mydf <- tibble(group = c("x", "x", "x", "y", "z", "x", "x", "z"), 
                   item = c(1, 2, 2, 3, 2, 2, 2, 1))

mydf

# A tibble: 8 × 2
  group  item
  <chr> <dbl>
1     x     1
2     x     2
3     x     2
4     y     3
5     z     2
6     x     2
7     x     2
8     z     1

runs <- rle(mydf$group)

mydf %>% 
  mutate(run_id = rep(seq_along(runs$lengths), runs$lengths)) %>% 
  group_by(group, run_id) %>% 
  summarise(item = sum(item)) %>% 
  arrange(run_id) %>% 
  select(-run_id) 

Source: local data frame [5 x 2]
Groups: group [3]

  group  item
  <chr> <dbl>
1     x     5
2     y     3
3     z     2
4     x     4
5     z     1

你可以建立群組標識與rle ,但更容易的途徑是只使用data.table::rleid ,這會為你:

library(dplyr)

df %>% 
    group_by(group, 
             group_run = data.table::rleid(group)) %>% 
    summarise_all(sum)
#> # A tibble: 5 x 3
#> # Groups:   group [?]
#>    group group_run  item
#>   <fctr>     <int> <int>
#> 1      x         1     5
#> 2      x         4     4
#> 3      y         2     3
#> 4      z         3     2
#> 5      z         5     1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM