R错误:“要替换的项目数不是替换长度的倍数”

时间:2014-02-01 16:32:41

标签: r matrix

我对R很新。当值设置得较低时,我的脚本工作正常。我需要计算概率并且需要至少1,000,000个样本。我的第一个循环返回此错误:

Error in new.matrix[i, ] <- as.vector(table(million.rep[, i])) : number of items to replace is not a multiple of replacement length

我的剧本:

actual.prob <- c(.14, .14, .16, .13, .19, .24)
number.in.bag <- c(8,6,20,9,10,5)

million.rep <- replicate(1000000, sample(1:6, 58, replace= T, actual.prob))



new.matrix <- matrix(nrow= 1000000, ncol=6)
# Note to other readers... the above line throws the error.

for(i in 1:1000000){
new.matrix[i,] <- as.vector(table(million.rep [, i]))
}


y <- c()
for(i in 1:1000000){
y[i] <- sum(new.matrix[i,] == number.in.bag)
}
y
sum(y == 6)

1 个答案:

答案 0 :(得分:3)

table计算所有正在发生的元素。如果缺少1:6中的任何一个,则输出的长度将小于6,例如:

set.seed(1)

## first call; table output is length == 5
table(sample(1:6, size=10, replace=TRUE))
1 2 3 4 6 
1 2 1 3 3 

## second call; table output is length == 4
table(sample(1:6, size=10, replace=TRUE))
2 3 5 6
2 3 4 1

要绕过此行为,您可以使用factor定义levelsfactor(sample, levels=1:6)):

## third call using factors; table output is always length == 6
## please notice the "levels=1:6"
table(factor(sample(1:6, size=10, replace=TRUE), levels=1:6))
1 2 3 4 5 6 
2 2 3 1 0 2 

对于您的示例,您可以使用:

new.matrix[i,] <- as.vector(table(factor(million.rep [, i]), levels=1:6))