Back

Explore Courses Blog Tutorials Interview Questions
+1 vote
4 views
in R Programming by (11.4k points)

Let's say I have two columns of data. The first contains categories such as "First", "Second", "Third", etc. The second has numbers which represent the number of times I saw "First".

For example:

Category     Frequency
First        10
First        15
First        5
Second       2
Third        14
Third        20
Second       3


I want to sort the data by Category and sum the Frequencies:

Category     Frequency
First        30
Second       5
Third        34


How would I do this in R?

1 Answer

+1 vote
by (32.3k points)

You can also use the dplyr package for that purpose:

library(dplyr)

x %>% 

  group_by(Category) %>% 

  summarise(Frequency = sum(Frequency))

#Source: local data frame [3 x 2]

#

#  Category Frequency

#1    First       30

#2   Second         5

#3    Third       34

Also, the recently added dplyr::tally() now makes this easier than ever:

tally(x, Category)

Category     n

First        30

Second       5

Third        34

Related questions

+5 votes
1 answer
+1 vote
1 answer
0 votes
1 answer
0 votes
1 answer

Browse Categories

...