[R] How to Standardise the x/y coordinates to the unit square?

Peter Dalgaard P.Dalgaard at biostat.ku.dk
Tue Sep 18 11:13:13 CEST 2007


张志杰 wrote:
> Dear Rusers, I want to standardise the values of x/y coordinates to the unit square, i.e. make the x-values all lie within [0,1] and all the y-values lie within [0,1] in the bottom example.  I had thought to use scale() function to do it, but it seems that it's used to standardise a variable and the scaled value was not within [0,1]. OR, i can divide x/y-values by their maximum value to get it.  I'm not sure about it.#Example data 

> data <- matrix(1:10, nc=2)
> data<-as.data.frame(data)
> names(data)<-c('x','y')

> > data
>   x  y
> 1 1  6
> 2 2  7
> 3 3  8
> 4 4  9
> 5 5 10 

>  I'd appreciate your help.
(Beware line formatting in your emails)

You can actually use scale(), but it is hardly worth it and an abuse of
concepts. Just write a little function for the actual scaling and apply
it to each column.

st <- function(x)(x-min(x))/(max(x)-min(x))
data.frame(lapply(data,st))

Or,

d.min <- apply(data,2,min)
d.max <- apply(data,2,max)
sweep(sweep(data, 2, d.min, "-"), 2, d.max - d.min, "/")

or, same thing using scale()

scale(data, center=d.min, scale=d.max - d.min)

>  
> --
> Kind Regards,
> John Chang
> 	[[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.
>   


-- 
   O__  ---- Peter Dalgaard             Øster Farimagsgade 5, Entr.B
  c/ /'_ --- Dept. of Biostatistics     PO Box 2099, 1014 Cph. K
 (*) \(*) -- University of Copenhagen   Denmark          Ph:  (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)                  FAX: (+45) 35327907



More information about the R-help mailing list