Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read a .CSV file with netlogo?

Tags:

csv

netlogo

I'm starting in netlogo these days, so I've got some problems that I didn't find how to solve them. I have to read a huge .csv file, got this code on the web:

to openFile
file-open "testeCsv.csv"
set csv file-read-line
set csv word csv ","  ; add comma for loop termination 

let mylist []  ; list of values 
  while [not empty? csv] 
  [
    let $x position "," csv 
    let $item substring csv 0 $x  ; extract item 
    carefully [set $item read-from-string $item][] ; convert if number 
    set mylist lput $item mylist  ; append to list 
    set csv substring csv ($x + 1) length csv  ; remove item and comma 
    set fileList mylist
  ] 
  set fileList mylist
  show fileList
end

This file contains this line: "1;0;0;65;0;2;45;0;-0,018961934" The output of this code is: "1 18961934" Help :/

like image 227
Maíra Araújo Avatar asked Jan 09 '23 09:01

Maíra Araújo


1 Answers

First of all, CSV means comma separated values with a point decimal separator, not semi-colon separated values with a comma decimal separator. See RFC 4180. Although some have resisted this for nationalistic reasons, the scientific community needs to adopt the existing standard. Agent-based modeling is part of the scientific community.

Now let's analyze what happen when you parse your file with this code. It reads the line as a string into your csv variable. It sets $x to 20 and extract the substring up to the comma. The use of read-from-string treats "1;0;0;65;0;2;45;0;-0" as if it had been typed at the command center, so you just get the number 1, since everything from the first semicolon onwards is a comment. The 1 is put into mylist and the csv variable is shortened to 018961934. When this is read, you get 18961934 because NetLogo ignores the leading 0.

This all happens because you do not have a real CSV file. So you need to use a real CSV file if you want to use this code to parse it.

like image 87
Alan Avatar answered Jan 16 '23 18:01

Alan