Let's say I have 2x matrices:
x <- matrix(rep(1:5, 2), ncol=5, byrow=T)
prob <- matrix(rep(0, each=5, 2), ncol=5, byrow=T)
prob[1, 3] <- 1
prob[2, 4] <- 1
> x
[,1] [,2] [,3] [,4] [,5]
[1,] 1 2 3 4 5
[2,] 1 2 3 4 5
> prob
[,1] [,2] [,3] [,4] [,5]
[1,] 0 0 1 0 0
[2,] 0 0 0 1 0
I want to perform "row-wise" sampling from the matrices with sample()
. For example, sample
will select one value from each row of x
using the probabilities in the same row of prob
. In the above example, I want sample
to return c(3,4)
every time because the probability has been set to 3=100% for row 1 and 4=100% for row 2.
However, when I run sample(x, prob=prob, size=nrow(x))
, I receive 3
and 4
is any order:
> sample(x, prob=prob, size=nrow(x))
[1] 4 3
> sample(x, prob=prob, size=nrow(x))
[1] 3 4
How can I perform "row-wise" sampling of the matrix x
?
One option with mapply
and asplit
mapply(sample, asplit(x, 1 ), prob = asplit(prob, 1), size = 1)
#[1] 3 4
You can use vapply
(safer by specifying what you're expecting) to loop over each row:
x <- matrix(rep(1:5, 2), ncol=5, byrow=T)
prob <- matrix(rep(0, each=5, 2), ncol=5, byrow=T)
prob[1, 3] <- 1
prob[2, 4] <- 1
vapply(seq_len(nrow(x)), function(i) {
sample(x[i, ], prob = prob[i, ], size = 1)
}, FUN.VALUE = numeric(1)
)
#> [1] 3 4
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.