I have a dataframe x
in R
ID Name Code
1 John aa1
1 Sue aa2
1 Mike aa2
1 Karl aa3
1 Lucy aa1
I would like to add an extra column to this dataframe counting the number of times each Code
value appears:
ID Name Code Code_frequency
1 John aa1 1
1 Sue aa2 2
1 Mike aa2 2
1 Karl aa3 1
1 Lucy aa4 1
I've tried using various combinations of mutate
and count
but I get error messages saying that I've used the wrong data type: no applicable method for 'count' applied to an object of class "character"
I've also seen that dplyr has the summarise
function but I need to preserve the layout of the dataframe as this will be exported from R as each row needs to be manually checked.
Is there a way to do this in R? A dplyr solution would fit easily into the rest of the code I have but I would welcome suggestions from other libraries as well.
CodePudding user response:
Using the n()
function:
x %>%
group_by(Code) %>%
mutate(Code_frequency = n()) %>%
ungroup()