Loading duplicates/ merging variables

Viewed 35

I'm loading animal data with a lot of duplicates which I'm trying to merge into one agent representing a single animal. The csv file looks like this:

Animal ID - Group ID

1 - A

2 - A

3 - A

4 - A

1 - B

2 - B

And for this example, i'm hoping to produce 4 unique animal agents that have a list of the groups they are associated with. Animal 1's list would be [A, B] and Animal 4's list would be just [A].

So far, I'm loading the csv using:

   csv:from-row file-read-line
   create-animal 1 [
        set Animal-ID item 0 data
        set group-ID item 1 data]


Which produces 6 animals with one group id each.

But how should I cull the duplicate animals?

1 Answers

If you have a csv that looks like:

id, group
1,A
2,A
3,A
4,A
1,B
2,B

You can load the csv as a list, pull unique animals, then filter the original list using the unique animal ids to grab the unique groups to which that animal belongs:

extensions [ csv ]

breed [ animals animal ]

animals-own [ animal-id group-id ]

to setup 
  ca
  
  ; Load animal data as a list of lists, drop the headers
  let animalData but-first csv:from-file "exampleAnimals.csv"
  print animalData
  
  ; Get the unique animal ids
  let animalIds remove-duplicates map [ i -> first i ] animalData
  print animalIds
  
  foreach animalIds [ id ->
    create-animals 1 [
      
      ; Set the id
      set animal-id id
      
      ; Filter the animal data by the id of the current animal
      let filtered filter [ row -> first row = id ] animalData
         
      ; Map to pull the group id as a list and assign to the animal
      set group-id map [ i -> last i ] filtered
      
      fd 1
    ]    
  ]
  reset-ticks
end

Hope that helps!

enter image description here

Related