NetLogo:将表结果导出到CSV

问题描述

该模型的目的是探索北洛矶山脉中灰狼的潜在扩散模式。在模型中,灰狼具有ph-memory属性,该属性对应于空间数据表。

extensions [ gis table csv]

wolves-own [
  ...
  ph-memory ;; wolves' patch-hunting memory,table includes the patch's hash-id (KEY) and pack-id (VALUE)
  ...   
]

to initialize-wolf  [  new-pack-id  ]
    ...
    set ph-memory     table:make
    ...
end

to setup
  clear-all
  setup-gis

  file-open (word "Ph-memory-for-run-" behaviorspace-run-number ".csv")
  ...
end

to go
  if not any? wolves [stop]
  ask wolves [    
    where-am-i
  ...
  file-write (table:to-list ph-memory)
end

to where-am-i
 let patch-hash-id ([hash-id] of patch-here)       ;;Updates the hash-id of the patch the wolf is currently on
    if not table:has-key? ph-memory patch-hash-id
    [table:put ph-memory patch-hash-id pack-id]             
end

当我打开Excel文件查看结果时,整个表都将导出到单个单元格中。不幸的是,这使数据分析无济于事,因为我无法轻松处理数据。

excel output

我的问题是:是否可以将数据表结果导出到excel中,并将数据分解成单个单元格/离散数据对(例如[patch-hash-id,pack-id])?我开始手动将数据重新格式化为列,但这非常繁琐!

ideal results

有人建议我如何有效地导出数据吗?

任何帮助将不胜感激!

解决方法

这里有两个问题。 file-write不会在输出末尾添加回车符,因此连续的file-write会将所有字符串都排成一行。此外,Excel需要一个CSV文件,其中每行的值都用逗号分隔,table:to-list生成ID /值对列表列表,但不会用逗号分隔值。 CSV扩展名可以很好地与csv:to-string配合使用,并且file-print提供了回车符。以下代码应显示它们如何组合在一起。

extensions [table csv]
globals [ph-memory]

to setup
  clear-all
  set ph-memory table:from-list [[1 2] [3 4] [5 6]]
  reset-ticks
end

to go
  file-open "c:/users/cstaelin/desktop/testfile.csv"
  file-print csv:to-string table:to-list ph-memory
  file-close
end

4次打勾后,csv文件看起来像

1,2
3,4
5,6
1,6

Excel会正确打开它。