[R] Utility function to apply a scale object on another data frame

E- Cognium ecognium at gmail.com
Sun Jul 17 08:05:41 CEST 2011


Thanks, Joshua. This is exactly what I was looking for.

On Sat, Jul 16, 2011 at 11:17 AM, Joshua Wiley <jwiley.psych at gmail.com> wrote:
>
> Hi "e",
>
> Here is a simple function to use the attributes from one scaled object
> to scale another.
>
>
> x = data.frame(a=1:10,b=11:20)
> y = data.frame(a=2:11,b=12:21)
> s <- scale(x)
>
> ## function to scale x using attributes from trained
> scale2 <- function(x, trained) {
>  x <- as.matrix(x)
>  x <- sweep(x, 2L, attr(trained, "scaled:center"), FUN = "-")
>  x <- sweep(x, 2L, attr(trained, "scaled:scale"), FUN = "/")
>  attr(x, "scaled:center") <- attr(trained, "scaled:center")
>  attr(x, "scaled:scale") <- attr(trained, "scaled:scale")
>  return(x)
> }
>
> ## scale y from s
> scale2(y, s)
>
> HTH,
>
> Josh
>
> On Sat, Jul 16, 2011 at 1:08 AM, E- Cognium <ecognium at gmail.com> wrote:
> > Hi Everyone,
> >
> > I would like to scale a data frame and then using the same scaling
> > parameters scale on another data frame. This will be helpful in scaling the
> > test dataset based on train dataset's scaling parameters. I couldn't find
> > any utility functions that do this. Any suggestions on how to approach this
> > problem?
> >
> > x = data.frame(a=1:10,b=11:20)
> > y = data.frame(a=2:11,b=12:21)
> > s <- scale(x)
> > ###
> > ### would like scale 'y' using the parameters contained in 's'
> >
> > Thanks,
> > -e
> >
> >        [[alternative HTML version deleted]]
> >
> > ______________________________________________
> > 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.
> >
>
>
>
> --
> Joshua Wiley
> Ph.D. Student, Health Psychology
> University of California, Los Angeles
> https://joshuawiley.com/



More information about the R-help mailing list