Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/80.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 按列模拟二项分布_R_Matrix_Simulation - Fatal编程技术网

R 按列模拟二项分布

R 按列模拟二项分布,r,matrix,simulation,R,Matrix,Simulation,我想为矩阵的每一列模拟数字0和1的二项分布。每列的成功概率都会发生变化。第1列的成功概率为1/ncol(矩阵)。第2列的成功概率为2/ncol(矩阵) 我尝试了几种不同的方法来生成我要查找的数据,但我要么得到警告,要么得到第一列的数字列表,而不是整个矩阵 更好的是能够使用概率矩阵,而不是像1/ncol(矩阵)这样的东西 假设我想要一个200行乘1000列的矩阵。对于每一列,我想使用概率矩阵中元素定义的概率生成0和1的二项分布。在由概率矩阵的第一个元素定义的第1列中得到1的概率为.001。第2列中

我想为矩阵的每一列模拟数字0和1的二项分布。每列的成功概率都会发生变化。第1列的成功概率为
1/ncol(矩阵)
。第2列的成功概率为
2/ncol(矩阵)

我尝试了几种不同的方法来生成我要查找的数据,但我要么得到警告,要么得到第一列的数字列表,而不是整个矩阵

更好的是能够使用概率矩阵,而不是像1/ncol(矩阵)这样的东西

假设我想要一个200行乘1000列的矩阵。对于每一列,我想使用概率矩阵中元素定义的概率生成0和1的二项分布。在由概率矩阵的第一个元素定义的第1列中得到1的概率为.001。第2列中得到1的概率由概率矩阵的第二个元素定义,为.002,等等。我不确定我应该在
matrix()
内还是在
apply()
内执行
rbinom()
或其他操作

    datasim = matrix(0, nrow=200, ncol=1000)
    colnames(datasim) = c(1:1000)
    prob.matrix = as.matrix(c(1:1000))
    prob.matrix = prob.matrix/1000
    newdatasim = apply(???, 2, function(x) { rbinom(??, 1, prob.matrix)})

请帮忙,谢谢

问题矩阵
用作向量比用作矩阵更简单。下面是一个较小的示例:

sapply(1:10/10,function(p) rbinom(20,1,p))
如果你想预先分配一个矩阵

set.seed(42)
datasim     <- matrix(,20,10)
datasim[,]  <- sapply(1:10/10,function(p) rbinom(20,1,p))

prob.matrix
用作向量比用作矩阵更简单。下面是一个较小的示例:

sapply(1:10/10,function(p) rbinom(20,1,p))
如果你想预先分配一个矩阵

set.seed(42)
datasim     <- matrix(,20,10)
datasim[,]  <- sapply(1:10/10,function(p) rbinom(20,1,p))

编辑:以下是我找到的解决方案之一。弗兰克的解决方案也有效。谢谢大家!

#Generate matrix with 200 rows x 1000 columns
#Each column has a binomial distribution of 0's and 1's
#The probability is determined by the column number divided by the total number of columns
datasim = matrix(0, nrow=200, ncol=100)
datasim[1:10,1:10]
probmatrix = col(datasim)/1000 
probmatrix[1:10,1:10]
datasim2 = matrix(rbinom(200 * 1000,1,probmatrix), nrow=200, ncol=1000, byrow=FALSE)
datasim2[1:10,1:10]

编辑:以下是我找到的解决方案之一。弗兰克的解决方案也有效。谢谢大家!

#Generate matrix with 200 rows x 1000 columns
#Each column has a binomial distribution of 0's and 1's
#The probability is determined by the column number divided by the total number of columns
datasim = matrix(0, nrow=200, ncol=100)
datasim[1:10,1:10]
probmatrix = col(datasim)/1000 
probmatrix[1:10,1:10]
datasim2 = matrix(rbinom(200 * 1000,1,probmatrix), nrow=200, ncol=1000, byrow=FALSE)
datasim2[1:10,1:10]

嗯,刚刚注意到你在问题中加入了一个解决方案。。。如果可以的话,你应该将其转换为单独的答案(发帖后8小时)。嗯,刚刚注意到你在问题中加入了一个解决方案。。。如果可以的话,你应该将其转换为单独的答案(发帖后8小时)。