3

R - apply 系列中是否有任何函数可以为矩阵的每个条目计算 FUN ?我有概率n x m矩阵——我可以使用,来采样, 但我不确定这个函数是否正常工作,因为我认为它应该是:MM[i, j] = pP(x = 1) = pP(x = 0) = 1 - pMapply
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
4

1 回答 1

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))
于 2013-03-25T22:04:46.170 回答