Another way is to use tidyverse functions:
- grouping first using
group_by() , and counting the appearance of the second variable with tally() - sorted by number of occurrences using
arrange() - summarizing and selecting the first row using
summarize() and first()
Thus:
df1 %>% group_by(id, v1) %>% tally() %>% arrange(id, desc(n)) %>% summarize(freq = first(v1))
This will only give you a comparison (which I find cleaner):
# A tibble: 2 x 2 id freq <dbl> <fctr> 1 1 b 2 2 c
Then you can left_join create the original data frame with this table.
slhck source share