Percentage of a maximum value within a group

14 views
Skip to first unread message

Sam Albers

unread,
Apr 23, 2015, 10:59:17 AM4/23/15
to manipulatr
Hello there,

I am sort of running in circle with a trouble as I know there is a better way than my current moethod but can't seem to figure it out. I'd like to figure out the "percentage of a maximum value within a group". Using the iris dataset here is what I am currently doing:

library(plyr)

iris1<-merge(
  ddply(iris, .(Species), summarize,
      maxPetal.Width=max(Petal.Width)
      ),
  iris, by=c("Species")
)

iris1$PerMax<-round(iris1$Petal.Width/iris1$maxPetal.Width, 2)
iris1

However, this seems cumbersome and I feel like there is a way to do this all while one instance of ddply. Can anyone recommend a better way of getting at this?

Thanks in advance!

Sam

Hadley Wickham

unread,
Apr 23, 2015, 11:13:37 AM4/23/15
to Sam Albers, manipulatr
Hint: try mutate instead of summarise.
Hadley
> --
> You received this message because you are subscribed to the Google Groups
> "manipulatr" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to manipulatr+...@googlegroups.com.
> To post to this group, send email to manip...@googlegroups.com.
> Visit this group at http://groups.google.com/group/manipulatr.
> For more options, visit https://groups.google.com/d/optout.



--
http://had.co.nz/

Sam Albers

unread,
Apr 23, 2015, 11:49:55 AM4/23/15
to Hadley Wickham, manipulatr
A fairly comprehensive hint.

Using mutate:

ddply(iris, .(Species), mutate,
      per = round(Petal.Width/max(Petal.Width),2)
)

Thanks Hadley!!!

Sam
Reply all
Reply to author
Forward
0 new messages