簡體   English   中英

如何將 tibble 中的向量分組並匯總為單個向量?

[英]How to group_by and summarise vectors inside a tibble into a single vector?


tibble(x = rep(1:3, 2),
       y = list(1:5, 1:10, 10:20, 20:40, 1:50, 5:10)) -> df

df
#> # A tibble: 6 × 2
#>       x y         
#>   <int> <list>    
#> 1     1 <int [5]> 
#> 2     2 <int [10]>
#> 3     3 <int [11]>
#> 4     1 <int [21]>
#> 5     2 <int [50]>
#> 6     3 <int [6]>

我想 group_by 'x' 並將每個組的向量匯總為一個向量。 我嘗試使用 c(),但沒有幫助。

df %>% 
  group_by(x) %>% 
  summarise(z = c(y))
#> `summarise()` has grouped output by 'x'. You can override using the `.groups`
#> argument.
#> # A tibble: 6 × 2
#> # Groups:   x [3]
#>       x z         
#>   <int> <list>    
#> 1     1 <int [5]> 
#> 2     1 <int [21]>
#> 3     2 <int [10]>
#> 4     2 <int [50]>
#> 5     3 <int [11]>
#> 6     3 <int [6]>

我還想要一個組中的元素聯合或應用於這些類型的數據集的任何其他類似函數。

df %>% 
  group_by(x) %>% 
  summarise(z = union(y))
#> Error in `summarise()`:
#> ! Problem while computing `z = union(y)`.
#> ℹ The error occurred in group 1: x = 1.
#> Caused by error in `base::union()`:
#> ! argument "y" is missing, with no default

如果您希望數據保持嵌套,您可以這樣做

df %>% 
  group_by(x) %>% 
  summarise(z = list(unlist(y)))

c()函數不起作用,因為它不會取消嵌套列表。 例如,比較

c(list(1:3, 4:5))
unlist(list(1:3, 4:5))

c函數不返回單個向量。 unlist可以。 這很重要,因為您的函數將在您使用summarize時收到匹配行值的列表。

另請注意,如果您離開list() ,則不再嵌套這些值

df %>% 
  group_by(x) %>% 
  summarise(z = unlist(y))
#        x     z
#    <int> <int>
#  1     1     1
#  2     1     2
#  3     1     3
#  4     1     4
#  5     1     5
#  6     1    20
#  7     1    21
#  ...

暫無
暫無

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

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