Eekhout, I. wrote on 09/19/2011 10:16:17 AM:
>
> Hi all,
>
> I would like to replace the for loop in the code below with a function
> to improve the speed and to make the script more efficient.
> The loop creates a vector of integers (x) with the probability of f for
> each integer.
> The length of f is variable, but sums to 1.
> I tried to use a function with optional arguments which did not work.
>
> Here is the code:
>
> f <- data.matrix(c(0.5,0.15,0.35))
> u <- runif(50)
> x <- data.matrix(rep(1, n))
> fc <- 0
> for(i in 1:length(f)) {
> fc <- fc + f[i]
> cf <- ifelse(u>fc,1,0)
> x <- x + cf
> }
> x
>
> Can anyone help me with this translation?
> Thanks in advance,
>
> Iris
There was no "n" in the sample code you shared. I assumed n=50.
n <- 50
f <- data.matrix(c(0.5, 0.15, 0.35))
u <- runif(n)
res <- outer(u, cumsum(f), ">")
x <- rowSums(res) + 1
x
Jean
[[alternative HTML version deleted]]