R错误: "number of items to replace is not a multiple of replacement length"

标签 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)

最佳答案

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(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))

关于R错误: "number of items to replace is not a multiple of replacement length",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21500585/

相关文章:

r - 转置列表列表

matlab - 如何在 MATLAB 中创建基于向量的三角矩阵?

r - R中二进制变量的相关分析

matlab - 查找矩阵中多个项目的索引?

java - 数独需要帮助构建可见矩阵

regex - 提取以某个符号结尾但没有此符号的子字符串

r - ggplotly 和 facet_wrap 的 X 轴错误

r - R 中列表元素的惰性求值

r - 获取列表的子列表

matrix - 为什么回代 Solve[] 的结果没有给出预期的结果?