I have the following dataframe:
No Name Fruit Country
1 Tom Pear France
2 Tom Pear France
3 Tom Pear Poland
4 Bob Kiwi Poland
5 Bob Pear France
6 Ann Pear France
7 Ann Pear Poland
8 Dod Pear Poland
7 Dod Plum Poland
8 Dod Plum Poland
9 Dod Pear Germany
10 Dod Kiwi Estonia
How can I, for each unique name, count how many unique values there are in the fruit column and then add this number as a column to the dataframe?
The output I would like to get is this:
No Name Fruit Country Unique
1 Tom Pear France 1
2 Tom Pear France 1
3 Tom Pear Poland 1
4 Bob Kiwi Poland 2
5 Bob Pear France 2
6 Ann Pear France 1
7 Ann Pear Poland 1
8 Dod Pear Poland 3
7 Dod Plum Poland 3
8 Dod Plum Poland 3
9 Dod Pear Germany 3
10 Dod Kiwi Estonia 3
I tried
df %>%
group_by(Name, Fruit) %>%
mutate(unique = n()) %>%
ungroup()
But the above does not work the way I wanted it to.