R - apply 系列中是否有任何函数可以为矩阵的每个条目计算 FUN ?我有概率n x m
矩阵——我可以使用,来采样,
但我不确定这个函数是否正常工作,因为我认为它应该是:M
M[i, j] = p
P(x = 1) = p
P(x = 0) = 1 - p
M
apply
apply(M, 1, function(x)(sample(0:1,length(x), replace = TRUE) ))
apply(M, 1, function(x)(sample(0:1,length(x), replace = TRUE, prob = x) ))
,但是第二个不起作用,除了有没有涉及其他apply
函数的更简单/更快的解决方案?
例子 :
> 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