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:> > bugsFRUIT 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: FRUIT ALIVE DEAD 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.
On Mon, May 16, 2011 at 11:56 PM, Jorge Ivan Velez wrote:
Hi Noelle,
Try using
count2 <- function(x) sum(x == 0)
or, for all at once (untested),
foo <- function(x) c( alive = sum(x == 1), dead = sum(x == 0))
with(bugs, tapply(SURVIVE, FRUIT, foo))
HTH,
Jorge
Hi Jorge,
The first bit of code didn't seem to work, but the second one did!
tapply worked but I also inserted "foo" into the aggregate code and
was also
able to add the "alive" and "dead" columns to my data.
Thanks very much for your help!
Noelle
- Hide quoted text -
--
View this message in context:
http://r.789695.n4.nabble.com/Zero-counts-in-an-aggregate-function-tp3528084p3528299.html
Sent from the R help mailing list archive at Nabble.com.