Search code examples
rdplyrgroup

in r dplyr select the first observation by group and create a list


I would like to select the first observation be group and create a list column.

For example:

df <- structure(list(Grp = c("A", "A", "A", "B", "B"), col1 = c(1, 
2, 3, 70, 80), col2 = c(4, 5, 6, 100, 110)), class = c("tbl_df", 
"tbl", "data.frame"), row.names = c(NA, -5L))

I would like to create a column whose first element is c(1,4) and second element is c(70, 100).

I tried:

df %>% group_by(Grp) %>% mutate(L = list(slice(1)))

But got an error.


Solution

  • A possible solution:

    library(dplyr)
    
    df %>% 
      group_by(Grp) %>% mutate(L = list(c(first(col1), first(col2)))) %>% 
      ungroup
    
    #> # A tibble: 5 × 4
    #>   Grp    col1  col2 L        
    #>   <chr> <dbl> <dbl> <list>   
    #> 1 A         1     4 <dbl [2]>
    #> 2 A         2     5 <dbl [2]>
    #> 3 A         3     6 <dbl [2]>
    #> 4 B        70   100 <dbl [2]>
    #> 5 B        80   110 <dbl [2]>