gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 04:39:26 25 4
gpt4 key购买 nike

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

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

如何使用线性代数来消除 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/

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