[R] a more elegant way to get percentages?

Liaw, Andy andy_liaw at merck.com
Thu Mar 13 15:50:21 CET 2008


From: Ted.Harding at manchester.ac.uk
> 
> Now that people have answered Monica's query, can someone help me?!!
> See below.
> 
> On 13-Mar-08 13:36:03, Monica Pisica wrote:
> > 
> > Hi,
> > 
> > I am trying to get percentages in a more elegant way. I have a
> > data.frame with locations and values (counts) of species at that
> > location. Each location is repeated for each species i have 
> values for
> > and i would like to get percentages of each species at that 
> location. I
> > am not sure if i am clear in my explanations so i will paste my code
> > below:
> > 
> >#####################
> > 
> >> x
> >    locat val
> > 1      a   5
> > 2      b   5
> > 3      b  15
> > 4      c   5
> > 5      c  20
> > 6      c   5
> > 7      c  10
> > 8      d   5
> > 9      d  15
> > 10     d  10
> 
> With Monica's dataframe as above, the answer would be 100*x[,1]/z
> where we want z to be c(5,20,20,40,40,40,40,30,30,30).
> 
> So, intending to give Monica a helpful answer, I tried
> 
> > apply(x,1,function(y) sum(x[x[,1]==y,2]))
>  1  2  3  4  5  6  7  8  9 10 
>  5 15 15 30 30 30 30 15 15 15 
> 
> and similarly
> 
> > apply(x,1,function(y) sum(x$val[x$locat==y]))
>  1  2  3  4  5  6  7  8  9 10 
>  5 15 15 30 30 30 30 15 15 15
> 
> 
> So why didn't this work? Where's my blind spot? Indeed, why
> did it gives the results it did?

One strategy is similar to what the piano teacher ask my son to try:
break it into small pieces.

apply() works on slices of the data, so take a slice where the answer
wasn't what you expected; e.g., the last row of x.  What gets passed
into the anonymous function is the 10th row of x, namely c(4, 10) (note
that apply() converts its first argument to a matrix or array).  so what
would you get when you test for equality to that?

Andy

 
> With thanks,
> Ted.
> 
> --------------------------------------------------------------------
> E-Mail: (Ted Harding) <Ted.Harding at manchester.ac.uk>
> Fax-to-email: +44 (0)870 094 0861
> Date: 13-Mar-08                                       Time: 14:15:34
> ------------------------------ XFMail ------------------------------
> 
> ______________________________________________
> 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.
> 
> 
> 


------------------------------------------------------------------------------
Notice:  This e-mail message, together with any attachme...{{dropped:15}}



More information about the R-help mailing list