csvnetlogo

How to retrieve values form csv file in Netlogo?


I'm using the CSV extension in Netlogo to bring numbers from a table. This file has a header and just one column with 1700 rows.

Each tick I have needs to grab the next number from the CSV table.

Example:

Table
67,
81,
54

for tick 1 set precipitation 67

for tick 2 set precipitation 81

for tick 3 set precipitation 54

and so on

How to do this?


Solution

  • An example is on the Official Help Page of the Extension, demonstrating how to extract values from a table with a single column. See the modified version below, including the suggestion of @SteveRailsback of using first to avoid the list output.

    extensions [csv]
    
    globals [ precipitation  ]
    
    to setup
      clear-all
      file-close-all ; Close any files open from last run
      file-open "test.csv"  
      set precipitation  csv:from-row file-read-line ; use it once to skip the header
      ; other setup goes here
      reset-ticks
    end
    
    to go
      if file-at-end? [ stop ]
      set precipitation first csv:from-row file-read-line
      tick
    end
    

    If you have a table with multiple columns I recommend storing the table headers and using it to identify the column index.

    extensions [csv]
    
    globals [
      csv_headers
      precipitation
      other_var
    ]
    
    to setup
      clear-all
      file-close-all ; Close any files open from last run
      file-open "test.csv"
      set csv_headers  csv:from-row file-read-line ; store headers to find right column
      reset-ticks
    end
    
    to go
      if file-at-end? [ stop ]
      let current_line csv:from-row file-read-line ; read the full line
      set precipitation item (position  "precipitation" csv_headers) current_line ; pick value from column with precipitation header
      set other_var item (position  "other_var" csv_headers) current_line ; repeat for another variable
      tick
    end