1

I have a dataframe df_workingFile:

group  | value
 a     |   1
 a     |   3
 b     |   2
 b     |   2

I want to add two new columns - one for the min and max for each group

group  | value | max | min
 a     |   1   |  3  |  1
 a     |   3   |  3  |  1
 b     |   2   |  2  |  2
 b     |   2   |  2  |  2

Right now I'm looping through each row and taking the min/max of the group's subset of data, but that's really slow with large datasets. What's an efficient way of doing this?

M--
  • 25,431
  • 8
  • 61
  • 93
NBC
  • 1,606
  • 4
  • 18
  • 31
  • 2
    `df$max = ave(df$value, df$group, FUN = max); df$min = ave(df$value, df$group, FUN = min)` – d.b Aug 16 '17 at 21:49
  • @Henrik I think you are a bit harsh on closing question as duplicates. Not necessarily this one, but I ran to two other posts today that you marked them as dupes which I wasn't quite sure about them to be duplicates of those threads. Of course you are the gold-badger ;) – M-- Aug 16 '17 at 22:41
  • @Masoud Thank you for your feedback! Please feel free to [cast a reopen vote](https://meta.stackexchange.com/questions/36415/how-do-you-reopen-a-closed-question) if you wish. (I just checked the ten most recent questions which I have dupehammered - so far no reopen votes on them, which may indicate that SO peers agree with my choice to close, as well as my choice of duplicate target). – Henrik Aug 17 '17 at 07:34
  • @Henrik Don't get me wrong. I wasn't saying they were wrong but harsh. Anyhow, you know that chance of reopening a question is really low and it's even lower when they have been dupehammered. All in all, it was my point of view and it can be right or wrong. – M-- Aug 17 '17 at 18:27

1 Answers1

4

With the dplyr package you can do the following:

df_workingFile %>% 
  group_by(group) %>% 
  mutate(max = max(value), min = min(value)) %>% ungroup()

  # A tibble: 4 x 4
   group value   min   max
   <chr> <dbl> <dbl> <dbl>
1      a     1     1     3
2      a     3     1     3
3      b     2     2     2
4      b     2     2     2
jtr13
  • 1,225
  • 11
  • 25