Search code examples
rgroup-bydatasetfrequencydplyr

R: How can I make a frequency column for a category in a category?


So I have lots of categories within one column. Within those categories, I have another category in another column. Variable 1 and 2 is what I have. I want the frequency column added.

Variable 1  ~      Variable 2     ~ Frequency

Category 1 ~       Red    ~        2 (because there are 2 red's in category 1)

~

Category 1   ~     Blue    ~       1

~

Category 1  ~      Red    ~        2 (again, because there are 2 red's in category 1)

~

Category 2   ~     Blue      ~     2 

~

Category 2  ~      Red      ~      1


~

Category 2    ~    Blue    ~       2

I want to add/mutate another column that will tell me what the frequency.

Thank you!


Solution

  • library(dplyr)
    your_data %>%
      group_by(Variable_1, Variable_2) %>%
      mutate(Frequency = n())