Reputation: 13
I have the 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 am trying to create a random number in each row where the upper limit is a number based on a variable value (in this case 1*Y based on each row's value for for Z)
I currently have:
samp<-function(x){
sample(0:1,1,replace = TRUE)}
x$randoms <- apply(m,1,samp)
which work works well applying the sample function independently to each row, but I always get an error when I try to alter the x in sample. I thought I could do something like this:
samp<-function(x){
sample(0:m$Z,1,replace = TRUE)}
x$randoms <- apply(m,1,samp)
but I guess that was wishful thinking.
Ultimately I want the result:
Y Z randoms
2 5 4
4 7 7
3 9 3
5 3 1
1 7 6
Any ideas?
Upvotes: 0
Views: 111
Reputation: 13
Based on @mathematical.coffee suggestion and my edited example this is the slick final result:
m <- matrix(c(2, 4, 3, 5, 1, 5, 7, 9, 3, 7), nrow=5, ncol=2,)
colnames(m) = c("Y","Z")
m <-data.frame(m)
samp<-function(x){
sample(Z + 1, 1)}
m$randoms <- sapply(m$Z + 1, sample, 1) - 1
Upvotes: 1
Reputation: 56915
The following will sample from 0 to x$Y
for each row, and store the 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 this y
), and calls sample(y + 1, 1)
on it.
Note that (e.g.) sample(y+1, 1)
will sample 1 random integer from the range 1:(y+1)
. Since you want a number from 0 to y
rather than 1 to y + 1
, we subtract 1 at the end.
Also, just pointing out - no need for replace=T
here because you are only sampling one value anyway, so it doesn't matter whether it gets replaced or not.
Upvotes: 1