Silke
Silke

Reputation: 177

Number of each element from a vector in R

I've got the following vector:

47 47 47 47 47 38 25 47 47 38

Now I search for a command in R that gives me how many times an element attend in the vector. So here I want to get the following return:

47 7
38 2
25 1

Does anybody know if there exists such a command?

Upvotes: 1

Views: 409

Answers (2)

Jaap
Jaap

Reputation: 83215

Another solution:

dat <- data.frame(a = sample(1:6, 1000, replace = TRUE))
summary(as.factor(dat$a))

  1   2   3   4   5   6 
160 166 191 170 164 149

You get the same result with:

table(dat$a)

  1   2   3   4   5   6 
160 166 191 170 164 149

Upvotes: 1

Paul Hiemstra
Paul Hiemstra

Reputation: 60924

I found the count function in the plyr package convenient:

library(plyr)
dat = data.frame(a = sample(1:6, 1000, replace = TRUE))
count(dat, 'a')
  a freq
1 1  153
2 2  148
3 3  160
4 4  178
5 5  177
6 6  184

Upvotes: 1

Related Questions