[R] applying data generating function
Peter Dalgaard
p.dalgaard at biostat.ku.dk
Sun Mar 7 23:04:23 CET 2004
Christophe Pallier <pallier at lscp.ehess.fr> writes:
> Fred J. wrote:
>
> >I need to generate a data set based on this equation
> >X(t) = 3.8x(t-1) (1-x(t-1)) + e(t), where e(t) is a
> >N(0,0,001) random variable
> >I need say 100 values.
> >
> > How do I do this?
>
> I assume X(t) and x(t) are the same (?).
>
> f<-function (x) { 3.8*x*(1-x) + rnorm(1,0,.001) }
> v=c()
> x=.1 # starting point
> for (i in 1:100) { x=f(x); v=append(v,x) }
>
> There may be smarter ways...
Yes, but the only really crucial one is to avoid the inefficient append by
preallocating the v:
v <- numeric(100)
x <- .1 ; for (i in 1:100) { x <- f(x); v[i] <- x }
apart from that you can use implicit loops:
x <- .1 ; v <- sapply(1:100, function(i) x <<- f(x))
or
z <- .1 ; v <- replicate(100, z <<- f(z))
(You cannot use x there because of a variable capture issue which is a
bit of a bug. I intend to fix it for 1.9.0.)
--
O__ ---- Peter Dalgaard Blegdamsvej 3
c/ /'_ --- Dept. of Biostatistics 2200 Cph. N
(*) \(*) -- University of Copenhagen Denmark Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk) FAX: (+45) 35327907
More information about the R-help
mailing list