1

I am trying to create a new variable in df that takes the mode of a variable with the same ID number. I want the output to look like this:

ID X MODE
1  3  2
1  2  2
1  2  2 
2  1  3
2  2  3 
2  1  3
2  3  3 
2  3  3
3  5  5
3  5  5

Any suggestions?

Rorx
  • 15
  • 5
  • First define a function that delivers mode (it's not a trivial task) then use `ave` to build a vector that applies that function to the X column by ID grouping. For SO you should first show what searching and coding efforts you have attempted if the task appears to be a homework problem. – IRTFM Nov 17 '20 at 16:54
  • 1
    Does this answer your question? [Most frequent value (mode) by group](https://stackoverflow.com/questions/29255473/most-frequent-value-mode-by-group) – Ben Nov 17 '20 at 16:59
  • Ah, apologies. Not at all a homework problem. Will do next time, was my first post. Thanks for the speedy replys – Rorx Nov 17 '20 at 17:11

1 Answers1

0

Maybe try this:

library(dplyr)
#Function
getmode <- function(v) {
  uniqv <- sort(unique(v),decreasing = T)
  uniqv[which.max(tabulate(match(v, uniqv)))]
}
#Code
newdf <- df %>% group_by(ID) %>% mutate(Mode2=getmode(X))

Output:

# A tibble: 10 x 4
# Groups:   ID [3]
      ID     X  MODE Mode2
   <int> <int> <int> <int>
 1     1     3     2     2
 2     1     2     2     2
 3     1     2     2     2
 4     2     1     3     3
 5     2     2     3     3
 6     2     1     3     3
 7     2     3     3     3
 8     2     3     3     3
 9     3     5     5     5
10     3     5     5     5
Duck
  • 39,058
  • 13
  • 42
  • 84