0

Here is the data

ID  Month   Sal
1   1       70
2   1       10
3   1       30
1   2       60
2   2       90
3   2       50
1   3       80
2   3       40
3   3       20

How do I find what is the max salary for each ID and what is the respective month?

I tried using aggregate for the max salary but how to find the respective month for each ID when he got the max salary

Ric S
  • 9,073
  • 3
  • 25
  • 51
harsha ray
  • 173
  • 1
  • 2
  • 10
  • 3
    @akrun I did not read your original comment, so not exactly sure what you mean. Just marked it so future users find the link. Although without an appropriate title to this question, that might not happen anyway. – MartijnVanAttekum Apr 15 '19 at 08:02
  • 4
    @akrun please stop discussing things that are not relevant to this post; if you want to discuss other posts: do it there – Jaap Apr 15 '19 at 08:10

1 Answers1

1

We can group_by the 'ID' and slice the row with the max 'Sal'

library(dplyr)
df1 %>% 
    group_by(ID) %>% 
    slice(which.max(Sal))
# A tibble: 3 x 3
# Groups:   ID [3]
#     ID Month   Sal
#  <int> <int> <int>
#1     1     3    80
#2     2     2    90
#3     3     2    50

data

df1 <- structure(list(ID = c(1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L), Month = c(1L, 
 1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L), Sal = c(70L, 10L, 30L, 60L, 
 90L, 50L, 80L, 40L, 20L)), class = "data.frame", row.names = c(NA, 
 -9L))
akrun
  • 874,273
  • 37
  • 540
  • 662