How to concatenate columns using group_by and summarize dplyr functions

Viewed 39

I have the following dataset "df1":

sex codfam class
1 100 1
2 100 2
1 110 1
2 110 4
1 120 4
2 120 5

I use "group_by" and "summarize" for grouping the codfam according to the min value of column "Class"

df <- df1 %>% 
group_by(codfam) %>%
summarize(fam_class = min(class))

It works fine and return me a result like this:

codfam class
100 1
110 1
120 4

Now I would get the value of column "sex" related to every codfam that function "summarize" keep in the dataset, something like this:

sex codfam class
1 100 1
1 110 1
2 120 4

I tried to use

   df <- df1 %>% 
   group_by(sex, codfam) %>%
   summarize(fam_class = min(class))

but unfortunately it doesn't work.

Any help or suggestions would be greatly appreciated, thanks in advance!

1 Answers

We can use slice_min

library(dplyr)
df1 %>% 
  group_by(codfam) %>%
  slice_min(n = 1, order_by = class) %>%
  ungroup
Related