Rob John
Rob John

Reputation: 287

Extract minimum and maximum values in each group and add a new column of texts using R

I have a dataframe (df) that I will like to transform:

No  Journey
101 1
101 2
101 3
101 4
121 1
121 2
121 3
132 1
132 2
132 3

Expected output:

No  Journey Comment
101 1   min
101 4   max
121 1   min
121 3   max
132 1   min
132 3   max

To get the above output, I know I can do the following to get two separate dataframes than can be combined together:

aggregate(df$Journey ~ df$No, data=df, min)
aggregate(df$Journey ~ df$No, data=df, max)

Then use ifelse() to write column "Comment", but I'm looking for a more elegant way than what I'm proposing.

Any ideas? Thanks

Upvotes: 0

Views: 27

Answers (1)

Karthik S
Karthik S

Reputation: 11546

Does this work:

df %>% group_by(No) %>% filter(Journey %in% c(min(Journey), max(Journey))) %>% arrange(No, Journey) %>% mutate(comment = case_when(row_number() == 1 ~ 'min', TRUE ~ 'max' ))
# A tibble: 6 x 3
# Groups:   No [3]
     No Journey comment
  <dbl>   <dbl> <chr>  
1   101       1 min    
2   101       4 max    
3   121       1 min    
4   121       3 max    
5   132       1 min    
6   132       3 max    

Upvotes: 2

Related Questions