Reputation: 2388
Hi I'm new to R and I'm trying to aggregate a list and count the total but not sure how to do it.
myList =c("A", "B", "A", "A", "B")
I can create a function that loops through the list and groups each category and counts them. But I'm sure there must be an easier way to group this so that I can get the category and the number each category. That is A would be 3 and B would be 2.
I tried using the function below but I believe I don't have the proper syntax.
aggr <-aggregate(myList, count)
Thanks for your help in advance.
Upvotes: 0
Views: 863
Reputation: 193677
I'm guessing that you're just looking for table
and not actually aggregate
:
myList =c("A", "B", "A", "A", "B")
table(myList)
# myList
# A B
# 3 2
tapply
can also be handy here:
tapply(myList, myList, length)
# A B
# 3 2
And, I suppose you could "trick" aggregate
in the following way:
aggregate(ind ~ myList, data.frame(myList, ind = 1), length)
# myList ind
# 1 A 3
# 2 B 2
If you're looking to understand why as well, aggregate
generally takes a data.frame
as its input, and you specify one or more columns to be aggregated grouped by one or more other columns (or vectors in your workspace of the same length as the number of rows).
In the example above, I converted your vector into a data.frame
, adding a dummy column where all the values were "1". I then used the formula ind ~ myList
(where ~
is sort of like "is grouped by") and set the aggregation function to length
(there is no count
in base R, though that function can be found in different packages).
Upvotes: 3