R - 创建子向量迭代

时间:2018-04-25 21:27:09

标签: r for-loop vectorization

我目前有这个for循环,我想要矢量化。它计算不同子向量中a的百分比数量。从[1:100]开始,[1:200],...总是在100步。

rolls.max <- 100000
a <- sample(1:6, size=rolls.max, replace=TRUE)

sixes.ratio <- c()
for(i in 1:(rolls.max/100)) {
  sixes.count <- table(a[1:(i*100)])[6]
  ratio <- sixes.count/(i*100)
  sixes.ratio <- c(sixes.ratio, ratio)
}

我认为最困难的部分是从每个子矢量得到6的计数。我试过这个:

rolls.max <- 100000
a <- matrix(sample(1:6, size=rolls.max, replace=TRUE))

subset.creator <- function(x, c) if (c!=0  && c%%100==0) { as.vector(table(x[1:(rolls[c/100])]))[6] }
sixes.count <- mapply(subset.creator, a, col(a))
# Converting the other lines won't be difficult I think

想要实现这一点,就是为函数subset.creator的每100次调用创建一个子向量。然后创建一个表并取第六列,得到6的计数,然后使用as.vector()

仅提取计数

但这只是给了我垃圾,而不是一个数为6的矢量。

1 个答案:

答案 0 :(得分:3)

如果你想在你的模拟掷骰子的每百个大块上创建一个“滚动记录”,解决问题的一种方法是创建一个代表你的截止点的“停止”向量,然后使用sapply在每个站点执行计算(在这种情况下,计算6s):

rolls.max <- 100000
a <- sample(1:6, size=rolls.max, replace=TRUE)

# a vector of "stops" at every hundredth entry of 'a'
stops <- seq(0, rolls.max, 100)[-1]

# counts of 6s from the first entry in 'a' to the values in 'stops'
count.6 <- sapply(stops, function(x) sum(a[1:x] == 6))

# ...or just as easily, the rolling proportion of 6s
prop.6 <- sapply(stops, function(x) mean(a[1:x] == 6))
相关问题