Friday, February 12, 2016

R: Count occurrences in vector

If you are having a vector and you want to count frequency of individual member (in other words, occurrences of each element) then you can do as following:

use hist() function:

x <- c(1,3,2,5,4,4,2,2,4,2,4,2,4,6,4,5,2)
 
x
 [1] 1 3 2 5 4 4 2 2 4 2 4 2 4 6 4 5 2
 
hist(x)
or use summary() function:

x <- factor(x)
 
x
 [1] 1 3 2 5 4 4 2 2 4 2 4 2 4 6 4 5 2
Levels: 1 2 3 4 5 6
 
summary(x)
1 2 3 4 5 6 
1 6 1 6 2 1
 
convert vector into factor and then call summary function.
OR

if you are working with characters then hist() won't be useful as it expects numeric elements so use summary() as shown below:
 
x <- c("devharsh","trivedi","R","C#","ASP.NET","R","C#","devharsh","R")
 
x <- factor(x)
 
summary(x)
 ASP.NET       C# devharsh        R  trivedi 
       1        2        2        3        1 

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.