首页 > 解决方案 > 将代理集的输出从循环返回到数据帧

问题描述

这是一个 RNetlogo 问题。假设,我在 Netlogo 中有一个代理集,其中每个农民代表一个补丁。我对补丁有一些“设置”和“运行”程序。我想去 10 滴答作响。在每个滴答声中,我希望针对代理(农民或补丁)的某些变量提取 R 中的值。以下是我的参数有限的代码 -

for(i in 10){
  NLCommand("set CropPirce ", 16, "setup")
  NLDoCommand(i, "go")
  print(NLGetAgentSet(c("ticks", "pxcor", "pycor", "Profit"), 
                           "patches with [a? = TRUE]")) # a? means if farmer adopted the crop
}

现在,如何将每个刻度步骤的打印值提取到数据框中?

提前致谢。

标签: for-loopnetlogornetlogo

解决方案


如果你想存储它 R,你可以创建一个空数据框,然后rbind每次调用NLGetAgentSet().

使用此测试模型:

to setup
  ca
  crt 3
  reset-ticks
end

to go
  ask turtles [
    rt random 90 - 45
    fd 1
  ]
  tick
end

制作你的空数据框:

vars <- c("ticks", "who", "pxcor", "pycor")

dfBase <- data.frame(matrix(
  NA,
  nrow = 0,
  ncol = length(vars),
  dimnames = list(NULL, vars)
))

运行模型(假设它已经打开):

NLCommand("setup")

for (i in 1:10) {
  NLCommand("go")
  
  dfBase <- rbind(dfBase, (NLGetAgentSet(vars, 'turtles')))
}

> head(dfBase); tail(dfBase)
  ticks who pxcor pycor
1     1   0    -1     0
2     1   1    -1    -1
3     1   2    -1     1
4     2   0    -2    -1
5     2   1    -1    -2
6     2   2    -2     1
   ticks who pxcor pycor
25     9   0    -8    -2
26     9   1    -1    -7
27     9   2    -7     3
28    10   0    -9    -2
29    10   1     0    -7
30    10   2    -8     2

推荐阅读