[R] Simplify simple code
Don MacQueen
macq at llnl.gov
Mon Apr 16 20:34:40 CEST 2007
For one thing, get rid of the for() loop.
The following may or may not be faster, and may or may not use more
memory (an issue if x1 and x2 are long), but it's easier to read.
n <- length(x1)
y <- numeric(n)
tmp <- x1>=5 & x1 <= 10 & x2 >= 5 & x2 <= 10
y[tmp] <- 0.631*x1[tmp]^0.55 * x2[tmp]^0.65
# and similarly for the other three conditions
I would put in a test at the beginning to make sure that x1 and x2
are the same length:
if (length(x1) != length(x2)) stop("Problem: x1 and x2 have
different lengths")
-Don
At 2:37 PM +0900 4/16/07, Dong-hyun Oh wrote:
>Dear expeRts,
>
>I would simplify following code.
>---------------------------------------------
>youtput <- function(x1, x2){
> n <- length(x1)
> y <- vector(mode="numeric", length=n)
> for(i in 1:n){
> if(x1[i] >=5 & x1[i] <= 10 & x2[i] >=5 & x2[i] <=10)
> y[i] <- 0.631 * x1[i]^0.55 * x2[i]^0.65
> if(x1[i] >=10 & x1[i] <= 15 & x2[i] >=5 & x2[i] <=10)
> y[i] <- 0.794 * x1[i]^0.45 * x2[i]^0.65
> if(x1[i] >=5 & x1[i] <= 10 & x2[i] >=10 & x2[i] <=15)
> y[i] <- 1.259 * x1[i]^0.55 * x2[i]^0.35
> if(x1[i] >=10 & x1[i] <= 15 & x2[i] >=10 & x2[i] <=15)
> y[i] <- 1.585 * x1[i]^0.45 * x2[i]^0.35
> }
> y
>}
>----------------------------------------------
>Anyone can help me?
>
>Sincerely,
>
>===========================================
>Dong H. Oh
>
>Ph. D Candidate
>Techno-Economics and Policy Program
>College of Engineering, Seoul National University,
>Seoul, 151-050, Republic of Korea
>
>E-mail:doriaba2 at snu.ac.kr
>Mobile: +82-10-6877-2109
>Office : +82-2-880-9142
>Fax: +82-2-880-8389
>
>______________________________________________
>R-help at stat.math.ethz.ch 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.
--
--------------------------------------
Don MacQueen
Environmental Protection Department
Lawrence Livermore National Laboratory
Livermore, CA, USA
More information about the R-help
mailing list