rm167
rm167

Reputation: 1247

R_ counting number of occurrence

This is my data frame 'mydf'

n       Results

1       l-m
2       m-m
3       l-m
4       l-m
5       l-m
6       l-m
7       l-m
8       l-m
9       l-m
10      l-m
11      m-l
12      l-m
...

there are thousands of rows. Now i want to count the number of occurrence of character strings 'l-m', 'm-m', 'm-l','l-l'(say this has 0 occurrence). I use the following method

table(mydf[,2])  
h-h h-m l-m m-h m-m 
11   7  29   2  13 

But I want to get something like:

a=number of occurrence of 'l-m'
b=number of occurrence of 'l-l' (even if it's zero)
...

Upvotes: 0

Views: 165

Answers (1)

Roland
Roland

Reputation: 132746

Set the levels of your factor explicitely:

x <- factor(c("l-m","m-m","l-m","l-m","l-m","l-m","l-m","l-m","l-m","l-m","m-l","l-m"),
            levels=c("l-l", "m-m", "l-m", "m-l"))

myTable <- table(x)
#x
#l-l m-m l-m m-l 
#0   1  10   1 

You can then extract counts using standard subsetting:

myTable["m-m"]
#m-m 
#  1

Upvotes: 5

Related Questions