Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

Count number of occurences for each unique value

Let's say I have:
v = rep(c(1,2, 2, 2), 25)


Now, I want to count the number of times each unique value appears. unique(v) returns what the unique values are, but not how many they are.

> unique(v)
[1] 1 2


I want something that gives me
length(v[v==1])
[1] 25
length(v[v==2])
[1] 75


but as a more general one-liner :) Something close (but not quite) like this:
#<doesn't work right> length(v[v==unique(v)])
by

2 Answers

vishaljlf39
Perhaps table is what you are after?
dummyData = rep(c(1,2, 2, 2), 25)

table(dummyData)
# dummyData
# 1 2
# 25 75

## or another presentation of the same data
as.data.frame(table(dummyData))
# dummyData Freq
# 1 1 25
# 2 2 75
sandhya6gczb
If you have multiple factors (= a multi-dimensional data frame), you can use the dplyr package to count unique values in each combination of factors:

library("dplyr")
data %>% group_by(factor1, factor2) %>% summarize(count=n())

It uses the pipe operator %>% to chain method calls on the data frame data.

Login / Signup to Answer the Question.