vars with different scales

8 views
Skip to first unread message

Joe Grzymski

unread,
Sep 29, 2011, 8:24:18 PM9/29/11
to ggplot2
All
I am plotting variables on the same plot using scaled common ranges.

Given a data.frame from the R data sets: "mtcars" it is simple to scale any one variable

range01<-function(x){
    rng<-range(x,na.rm=TRUE)
   (x-rng[1])/diff(rng)
}

mtcars<-mutate(mtcars,scaledhp=range01(hp))

is there a trivial way to scale hp according to its cylinder (cyl)
without individually scaling and then putting back together in a data.frame
like this:

>cyl4<-mtcars$cyl==4
> only4<-mtcars[cyl4,]
>only4<-mutate(only4,scaledhp=range01(hp))
>cyl6<-mtcars$cyl==6
> only6<-mtcars[cyl6,]
>only6<-mutate(only6,scaledhp=range01(hp))
>new<-rbind(only4,only6)
> str(new)
'data.frame':    18 obs. of  11 variables:
 $ mpg : num  22.8 24.4 22.8 32.4 30.4 33.9 21.5 27.3 26 30.4 ...
 $ cyl : num  4 4 4 4 4 4 4 4 4 4 ...
 $ disp: num  108 146.7 140.8 78.7 75.7 ...
 $ hp  : num  93 62 95 66 52 65 97 66 91 113 ...
 $ drat: num  3.85 3.69 3.92 4.08 4.93 4.22 3.7 4.08 4.43 3.77 ...
 $ wt  : num  2.32 3.19 3.15 2.2 1.61 ...
 $ qsec: num  18.6 20 22.9 19.5 18.5 ...
 $ vs  : num  1 1 1 1 1 1 1 1 0 1 ...
 $ am  : num  1 0 0 1 1 1 0 1 1 1 ...
 $ gear: num  4 4 4 4 4 4 3 4 5 5 ...
 $ carb: num  1 2 2 1 2 1 1 1 2 2 ...
> str(mtcars)
'data.frame':    32 obs. of  11 variables:
 $ mpg : num  21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 ...
 $ cyl : num  6 6 4 6 8 6 8 4 4 6 ...
 $ disp: num  160 160 108 258 360 ...
 $ hp  : num  110 110 93 110 175 105 245 62 95 123 ...
 $ drat: num  3.9 3.9 3.85 3.08 3.15 2.76 3.21 3.69 3.92 3.92 ...
 $ wt  : num  2.62 2.88 2.32 3.21 3.44 ...
 $ qsec: num  16.5 17 18.6 19.4 17 ...
 $ vs  : num  0 0 1 1 0 1 0 1 1 1 ...
 $ am  : num  1 1 1 0 0 0 0 0 0 0 ...
 $ gear: num  4 4 4 3 3 3 3 4 4 4 ...
 $ carb: num  4 4 1 1 2 1 4 2 2 4 ...


Thank you so much.
Joe

Brian Diggs

unread,
Sep 29, 2011, 8:48:03 PM9/29/11
to ggplot2
On 9/29/2011 5:24 PM, Joe Grzymski wrote:
> All
> I am plotting variables on the same plot using scaled common ranges.
>
> Given a data.frame from the R data sets: "mtcars" it is simple to scale any
> one variable
>
> range01<-function(x){
> rng<-range(x,na.rm=TRUE)
> (x-rng[1])/diff(rng)
> }
>
> mtcars<-mutate(mtcars,scaledhp=range01(hp))
>
> is there a trivial way to scale hp according to its cylinder (cyl)
> without individually scaling and then putting back together in a data.frame
> like this:

library("plyr")

new <- ddply(mtcars, .(cyl), mutate, scaledhp=range01(hp))


--
Brian S. Diggs, PhD
Senior Research Associate, Department of Surgery
Oregon Health & Science University

Reply all
Reply to author
Forward
0 new messages