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
答案 0 :(得分:9)
您可以将多个维度传递给apply
。如果要按行和列进行采样,请使用1:2
至于您从二项式解析中采样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
在这种情况下,rbinom
(与R
中的许多函数一样)被矢量化,当您传递矩阵时,它将为每个条目计算。然后,您必须强制回到所需的matrix
尺寸。
例如
matrix(rbinom(n=length(M),size=1,prob=M), nrow = nrow(M), ncol = ncol(M))