R - is there any function from apply family which could compute FUN for every entry of matrix ? I have n x m matrix M of probabilities - M[i, j] = p that P(x = 1) = p, P(x = 0) = 1 - p, to sample from M I could use apply,
apply(M, 1, function(x)(sample(0:1,length(x), replace = TRUE) ))
but I'm not sure if this function works properly because, I think it should be rather :
apply(M, 1, function(x)(sample(0:1,length(x), replace = TRUE, prob = x) ))
,but the second doesn't work, except that is there simpler/faster solution involving other then apply function ?
example :
> M=matrix(runif(10*4),10,4)
> M
[,1] [,2] [,3] [,4]
[1,] 0.4497123 0.74045206 0.8112949 0.33122848
[2,] 0.5416048 0.35812976 0.3877630 0.01491928
[3,] 0.7164970 0.15793958 0.1822459 0.07017764
[4,] 0.7965967 0.85600843 0.3129818 0.25698186
[5,] 0.8553264 0.06880133 0.4516520 0.14231129
[6,] 0.8667404 0.49394338 0.1331386 0.37769487
[7,] 0.9446913 0.87368456 0.3680256 0.92143709
[8,] 0.4251636 0.69126643 0.5355501 0.45516271
[9,] 0.7483549 0.04289660 0.7817728 0.37752422
[10,] 0.0218563 0.91304663 0.4800049 0.19477370
> apply(M, 1, function(x)(sample(0:1,length(x), replace = TRUE, prob = x) ))
Error in sample(0:1, length(x), replace = TRUE, prob = x) :
incorrect number of probabilities
> apply(M, 1, function(x)(sample(0:1,length(x), replace = TRUE) ))
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 1 0 0 1 0 0 1 1 0 0
[2,] 0 1 0 0 1 1 0 1 1 0
[3,] 0 1 0 1 1 0 1 1 1 1
[4,] 0 0 1 1 0 0 1 1 0 1
You can pass more than one dimension to apply. If you want to sample by rows and columns use 1:2
As for your sampling from a binomial distrution use rbinom
apply(M, 1:2, rbinom, size =1, n=1)
[,1] [,2] [,3] [,4]
[1,] 0 1 0 0
[2,] 1 0 0 1
[3,] 1 0 1 0
[4,] 1 0 1 0
[5,] 1 0 0 0
[6,] 1 0 0 1
[7,] 0 1 1 0
[8,] 1 1 0 1
[9,] 1 0 1 0
[10,] 0 0 0 1
In this case rbinom (as with many functions in R), is vectorized, and when you pass a matrix, it will compute for every entry. You will then have to coerce back to your required matrix dimensions.
For example
matrix(rbinom(n=length(M),size=1,prob=M), nrow = nrow(M), ncol = ncol(M))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With