Search code examples
rstringdataframecountunique

Counting number of specific strings in an R data frame


I have a data frame that has many columns, but the two columns I am interested in are major and department. I need to find a way to count the number of specific entries in a column. So my data frame looks something like

student_num    major          dept
123            child          education
124            child          education
125            special        education
126            justice        administration
127            justice        administration
128            justice        administration
129            police         administration
130            police         administration

What I want is a student count for each major and department. Something like

education   child   special    administration    justice    police
3           2       1          5                 3          2

I have tried several methods but nothing is quite what I need. I tried using the aggregate() function and the ddply() from plyr but they give me department as two - for two unique entries, education and administration. How can I count each unique entry and not how many unique entries there are?


Solution

  • You can try:

    library(dplyr)
    count(my_dataframe, major)
    count(my_dataframe, dept)