Count unique value and add column and use mutate

I want to count the unique names of the agents and then output them in an extra column FreqAgent like this:
agent | FreqAgent
David | 3
Kate | 2
Alma | 2

What is best practice to do this?

df <- data.frame(
        agent = as.character(c("David", "David", "David", "Kate", "Kate", "Alma", "Alma")),
        manager = as.character(c("Lisa", "Monica", "Karl", "Kianna", "Luna", "Kaylin", "Georgia")),
        team = as.character(c("Sales", "Sales", "Sales", "Billing", "Sales", "Sales", "Sales"))
)

df_n <- df %>% 
        mutate(FreqAgent=  ???)

Below is a way to accomplish this using mutate().

df_n <- df %>% 
  group_by(agent) %>%
  mutate(FreqAgent=  n()) %>%
  ungroup() %>%
  distinct(agent, FreqAgent)

df_n
#> # A tibble: 3 × 2
#>   agent FreqAgent
#>   <chr>     <int>
#> 1 David         3
#> 2 Kate          2
#> 3 Alma          2

Another approach is using the count() function.

df %>%
  count(agent, name = 'FreqAgent')
#>   agent FreqAgent
#> 1  Alma         2
#> 2 David         3
#> 3  Kate         2

Created on 2022-09-09 with reprex v2.0.2.9000

1 Like

Another way to do this, when a data.frame isn't immediately required:

DF <- data.frame(
  agent = as.character(c("David", "David", "David", "Kate", "Kate", "Alma", "Alma")),
  manager = as.character(c("Lisa", "Monica", "Karl", "Kianna", "Luna", "Kaylin", "Georgia")),
  team = as.character(c("Sales", "Sales", "Sales", "Billing", "Sales", "Sales", "Sales"))
)

table(DF) |> rowSums()
#>  Alma David  Kate 
#>     2     3     2

:sweat_smile: my intention to use mutate was to add FreqAgent to the complete DF without deleting e.g. manager and team.

@ scotty - Thanks this works for me:

df_n <- df %>%
group_by(agent) %>%
mutate(FreqAgent= n()) %>%
ungroup()

# A tibble: 7 × 4
  agent manager team    FreqAgent
  <chr> <chr>   <chr>       <dbl>
1 David Lisa    Sales           3
2 David Monica  Sales           3
3 David Karl    Sales           3
4 Kate  Kianna  Billing         2
5 Kate  Luna    Sales           2
6 Alma  Kaylin  Sales           2
7 Alma  Georgia Sales           2

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.