0

我正在尝试在 R 中构建一个(有效的)基于代理的模型。每个代理都有在列表中的 data.table 中捕获的信息。有没有比我有更有效的方法来做到这一点?这是一些简化的代码:

require(data.table)

# Setup simulation
numAgents <- 5
numIterations <- 10

# Create collection of agents which have a property someValue that we want to track through the simulation
agents <- vector("list", numAgents)

for(i in 1:numAgents) {
  agents[[i]] <- data.table(someValue1 = rep(as.integer(NA), numIterations), someValue2 = rep(as.integer(NA), numIterations))
}

# Iterate through simulation
for(i in 1:numIterations) {
  # Generate values for someValue1, someValue2 for the agents
  #   Note: This is just to give an idea of what will be involved
  #   Note2: The values depend upon history and other agents
  agentValues1 <- lapply(agents, function(x) {
                                   sum(x[, median(someValue1, na.rm = TRUE)], round(runif(1)), na.rm = TRUE)
                                 })
  agentValues2 <- ifelse(runif(numAgents) < as.integer(agentValues1)/max(as.integer(agentValues1)), 1, 0)

  # Update the agents history (I'm trying to optimize this)
  for(k in 1:numAgents) {
    set(agents[[k]], i, j = "someValue1", as.integer(agentValues1[k]))
    set(agents[[k]], i, j = "someValue2", as.integer(agentValues2[k]))
  }
}

也欢迎不使用 data.tables 列表的建议,但可能会稍微扩大问题的范围。

需要注意的是,值生成过程涉及(1)代理的多个属性(例如,someValue1 和 someValue2)(2)这些属性的历史,以及(3)其他代理的行为。它没有反映在示例代码中(还),因为我还没有想到一种简单的方法来反映它……我会尽可能更新。


[编辑] 修改代码以包含多个代理属性和样本值生成,这些都依赖于历史和其他代理。示例代码中的值生成过程本身没有意义,但旨在说明实际代码中的依赖类型。

4

1 回答 1

0

您可能会发现最好使用矩阵来存储代理值:

numAgents <- 5
numIterations <- 10

agents <- matrix(NA, nrow=numAgents, ncol=numIterations)

for(i in 1:numIterations) {
  agentValues <- as.integer(ceiling(runif(numAgents)*10))
  agents[,i] <- agentValues
}
于 2013-09-24T06:33:45.393 回答