user2288726
user2288726

Reputation: 3

Getting rid of a for loop in R

I would like to sample a given vector with different sets of probabilities without a loop. Is there a way to do this?

For example in this code I would like to replace the loop with some sort of apply() structure or anything really ..

a <- c(1,2,3)
p <- matrix(c(.1,.1,.8,.1,.8,.1,.8,.1,.1), nrow=3)
s <- matrix(ncol=5, nrow=3)
for(i in 1:nrow(p)){
s[i,] <- sample(a, size=5, replace=T, prob=p[i,])
}

thanks for the help!

Upvotes: 0

Views: 586

Answers (1)

Matthew Lundberg
Matthew Lundberg

Reputation: 42649

apply on p itself:

t(apply(p, 1, sample, x=a, size=5, replace=TRUE))
     [,1] [,2] [,3] [,4] [,5]
[1,]    3    3    1    3    3
[2,]    2    2    1    1    2
[3,]    1    1    1    1    1

Edit I had a functional::Curry in here, until flodel pointed out that it wasn't necessary, as apply gives an automatic curry by allowing named arguments via ....

Upvotes: 2

Related Questions