Variable sample upper value in R -


i have following matrix

m <- matrix(c(2, 4, 3, 5, 1, 5, 7, 9, 3, 7), nrow=5, ncol=2,)  colnames(x) = c("y","z") m <-data.frame(m) 

i trying create random number in each row upper limit number based on variable value (in case 1*y based on each row's value for z)

i have:

 samp<-function(x){     sample(0:1,1,replace = true)}      x$randoms <- apply(m,1,samp) 

which work works applying sample function independently each row, error when try alter x in sample. thought this:

samp<-function(x){         sample(0:m$z,1,replace = true)}          x$randoms <- apply(m,1,samp) 

but guess wishful thinking.

ultimately want result:

 y z randoms  2 5       4  4 7       7  3 9       3  5 3       1  1 7       6 

any ideas?

the following sample 0 x$y each row, , store result in randoms:

x$randoms <- sapply(x$y + 1, sample, 1) - 1 

explanation:

the sapply takes each value in x$y separately (let's call y), , calls sample(y + 1, 1) on it.

note (e.g.) sample(y+1, 1) sample 1 random integer range 1:(y+1). since want number 0 y rather 1 y + 1, subtract 1 @ end.

also, pointing out - no need replace=t here because sampling 1 value anyway, doesn't matter whether gets replaced or not.


Comments