# [R] Zero counts in an aggregate function

From: noellejm <noellejm_at_u.washington.edu>
Date: Mon, 16 May 2011 22:46:23 -0700 (PDT)

Dear R-users,

I've searched for an answer to my question, but so far haven't been able to find a solution. Its likely a simple issue, but have no idea how to do this.

A simplified version my (very large) data set looks like this:
>
> bugs

FRUIT SEED_ID SURVIVE

```1      1       A       1
2      1       B       1
3      1       C       1
4      1       D       0
5      1       E       1
6      1       F       0
7      2       A       1
8      2       B       1
9      2       C       1
10     2       D       1
11     2       E       1
12     2       F       1
13     3       A       0
14     3       B       0
15     3       C       0
16     3       D       0
17     3       E       0
18     3       F       0

```

What I would like to do is aggregate seeds per fruit and reorganize the SURVIVE data into counts.
I would like to add columns with counts of the number of 1s (alive) and 0s (dead) in each so that my data looks like this:

```1     1        4         2
2     2        6         0
3     3        0         6

```

I have managed do do this using "aggregate" with FUN=sum for the 1 values...

bugsALIVE<-aggregate(bugs\$SURVIVE,by=list(bugs\$FRUIT),FUN=sum,na.rm=TRUE)

...but am having trouble figuring out how to get counts of the 0 values since there is no built-in "count" function. I have tried to write my own function but I am fairly new to R and writing functions and have not figured out how to only count 0s within each value of "FRUIT"
Something like...

count<-function(x){length(x==0)}

However, when I try this it still counts all 6 seeds per fruit. How can I write a function to only count zero values for each value of "FRUIT"? Or is there a better/simpler way than using the aggregate function?

Any help is appreciated!
Thanks,
Noelle

```--
View this message in context: http://r.789695.n4.nabble.com/Zero-counts-in-an-aggregate-function-tp3528084p3528084.html
Sent from the R help mailing list archive at Nabble.com.

______________________________________________
R-help_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
```
Received on Tue 17 May 2011 - 06:46:45 GMT

This quarter's messages: by month, or sorted: [ by date ] [ by thread ] [ by subject ] [ by author ]

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Tue 17 May 2011 - 09:20:07 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.