mercredi 22 novembre 2017

Using sample() in R in a conditional way

I want to assign a random number of B for each number of A. The condition is that the numer assigned of B must be bigger than the corresponding number of A. Here is my code. Is there any way to do this faster?
I tried with the for loop and other ways with a worst result! Thanks a lot!

set.seed(123)
A <- rlnorm(10000,5,1) 
B <- rlnorm(100000,10,2)
df <- data.frame(NumPol=1:length(B), Cap=B)

pol_sel <- sapply(1:length(A), FUN = function(i) { 
sample(df$NumPol[which(df$Cap > A[i])], size=1, replace=TRUE) } )




Aucun commentaire:

Enregistrer un commentaire