0

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) ... 
1
  • 3
    I think a look at factor and levels may be relevant here. E.g. reply <- factor(c("yes", "yes"), levels = c("yes", "no")); table(reply). Commented Mar 31, 2014 at 11:56

1 Answer 1

5

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 
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you @Roland. From the result how can I abstract a single value. For example if I want to get the occurrence of 'm-m' and want to assign it for a variable 'a' how can I do it?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.