views:

1076

answers:

3

I'm looking to get a count for the following data frame:

> Santa
   Believe Age Gender Presents Behaviour
1    FALSE   9   male       25   naughty
2     TRUE   5   male       20      nice
3     TRUE   4 female       30      nice
4     TRUE   4   male       34   naughty

of the number of children who believe. What command would I use to get this?

(The actual data frame is much bigger. I've just given you the first four rows...)

Thanks!

+4  A: 

You could use table:

R> x <- read.table(textConnection('
   Believe Age Gender Presents Behaviour
1    FALSE   9   male       25   naughty
2     TRUE   5   male       20      nice
3     TRUE   4 female       30      nice
4     TRUE   4   male       34   naughty'
), header=TRUE)

R> table(x$Believe)

FALSE  TRUE 
    1     3
rcs
+1  A: 
sum(Santa$Believe)
Carl
A: 

The 'subset' function is a good way to do this. Broad utility and you don't have to parse a return value to get the result you need--so a good choice to wrap in a function. In your case:

v = nrow(subset(x, Believe==F))     # 'subset' returns a data.frame

and wrapped in an anonymous function:

>> fnx = function(fac, lev){nrow(subset(x, fac==lev))}

>> fnx(Believe, T)

>> 3
doug