Marco Turna
Marco Turna

Reputation: 23

Netlogo - Given an Agentset of 2+ Turtles, find the most frequent color

Given an agentset of two or more turtles, how do I find the most frequent color?

I would like to do something like that, if possible:

set my_color [mostfrequentcolor] of my_agentset

Upvotes: 2

Views: 167

Answers (3)

Seth Tisue
Seth Tisue

Reputation: 30453

You're looking for the modes primitive (https://ccl.northwestern.edu/netlogo/docs/dictionary.html#modes):

one-of modes [color] of my_agentset

It's "modes", plural, since there could be a tie. One way of breaking the tie is to use one-of to make a random selection.

Upvotes: 1

Nicolas Payette
Nicolas Payette

Reputation: 14972

Here are two more options, both making use of the table extension:

extensions [ table ]

to-report most-frequent-color-1 [ agentset ]
  report (first first
    sort-by [ [p1 p2] -> count last p1 > count last p2 ]
    table:to-list table:group-agents turtles [ color ])
end

to-report most-frequent-color-2 [ agentset ]
  report ([ color ] of one-of first
    sort-by [ [a b] -> count a > count b ]
    table:values table:group-agents turtles [ color ])
end

I'm not quite sure which one I prefer...

Upvotes: 1

Luke C
Luke C

Reputation: 10291

With this example setup:

to setup
  ca
  crt 10 [
    set color one-of [ blue green red yellow ]
  ]
  print most-frequent-color turtles 
  reset-ticks
end

You can make use of a to-report procedure to do this- details in comments:

to-report most-frequent-color [ agentset_ ]
  ; get all colors of the agentset of interest
  let all-colors [color] of agentset_

  ; get only the unique values
  let colors-used remove-duplicates all-colors

  ; use map/filter to get frequencies of each color
  let freqs map [ m -> length filter [ i -> i = m ] all-colors ] colors-used

  ; get the position of the most frequent color (ties broken randomly) 
  let max-freq-pos position ( max freqs ) freqs 

  ; use that position as an index for the colors used
  let max-color item max-freq-pos colors-used

  report max-color
end

Upvotes: 1

Related Questions