[R] A coding question

Ben Bolker bolker at ufl.edu
Fri Jun 2 15:26:57 CEST 2006


Uwe Ligges <ligges <at> statistik.uni-dortmund.de> writes:

> 
> xpRt.wannabe wrote:
> 
> > y <- replicate(10,replicate(8,sum(rnorm(rpois(1,5)))))
> > 
> > x - max(0,x-15) + max(0,x-90), where x represents the individual Normal
> > numbers.

> 
> y <- replicate(10, {
>          rp <- rpois(8, 5)
>          mysum <- sapply(rp, function(x) {
>              x <- rnorm(x)
>              x <- x - max(0, x-15) + max(0, x-90)
>              sum(x)
>          })
>       })
> 

  I think this can be boiled down a bit further.

x-max(0,x-15)+max(0,x-90)

if x>90:        x-(x-15)+(x-90) = x+15-90=x-75
if 15<x<90      x-(x-15)+0      = 15
if x<15         x-0+0           = x

therefore

tmpf <- function() {
  x <- rnorm(rpois(1,5))
  sum(ifelse(x>90,x-75,pmin(x,15)))
}

replicate(10,replicate(8,tmpf()))

(you could also generate 80 values and then break them
 up into segments of 8)

  Ben Bolker



More information about the R-help mailing list