gpt4 book ai didi

r - 如何在 R 中向量化比较而不是 for 循环?

转载 作者:行者123 更新时间:2023-12-02 21:36:44 24 4
gpt4 key购买 nike

我想运行离散时间模拟(下面的简化版本)。我生成一个人口成员数据框(每行一个成员)及其进入和退出网站的时间戳。然后我希望在每个时间间隔计算网站上有多少成员(member)。

目前,我正在循环时间,每秒计算有多少成员已进入但尚未退出。 (我还尝试过通过在每个间隔删除退出的成员来进行破坏性迭代,这需要更长的时间。我还了解我可以在循环中使用更大的时间间隔。)

如何使用线性代数消除 for 循环和多余的运行时间?我目前的方法不能随着人口的增加而很好地扩展,当然它与持续时间是线性的。

popSize = 10000
simDuration = 10000
enterTimestamp <- rexp(n = popSize, rate = .001)
exitTimestamp <- enterTimestamp + rexp(n = popSize, rate = .001)
popEvents <- data.frame(cbind(enterTimestamp,exitTimestamp))
visitorLoad <- integer(length = simDuration)
for (i in 1:simDuration) {
visitorLoad[i] <- sum(popEvents$enterTimestamp <= i &
popEvents$exitTimestamp > i)
if (i %% 100 == 0) {print(paste('Sim at',i,'out of',simDuration,
'seconds.',sep=' ') )}
}
plot(visitorLoad, typ = 'l', ylab = 'Visitor Load', xlab='Time Elapsed (sec)')

最佳答案

您可以获取不同时间进出的访客数量,然后使用累计和来计算特定时间的访客数量。这似乎满足了您对代码运行速度快的要求,尽管它没有使用线性代数。

diffs = rep(0, simDuration+1)

# Store the number of times a visitor enters and exits at each timestep. The table
# will contain headers that are the timesteps and values that are the number of
# people entering or exiting at the timestep.
tabEnter = table(pmax(1, ceiling(enterTimestamp)))
tabExit = table(pmin(simDuration+1, ceiling(exitTimestamp)))

# For each time index, add the number of people entering and subtract the number of
# people exiting. For instance, if in period 20, 3 people entered and 4 exited, then
# diffs[20] equals -1. as.numeric(names(tabEnter)) is the periods for which at least
# one person entered, and tabEnter is the number of people in each of those periods.
diffs[as.numeric(names(tabEnter))] = diffs[as.numeric(names(tabEnter))] + tabEnter
diffs[as.numeric(names(tabExit))] = diffs[as.numeric(names(tabExit))] - tabExit

# cumsum() sums the diffs vector through a particular time point.
visitorLoad2 = head(cumsum(diffs), simDuration)

关于r - 如何在 R 中向量化比较而不是 for 循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21199212/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com