```{r ch_opt, child="include/chunk_options.rmd", cache=FALSE}
```


```{r, echo = FALSE}
library(nlexperiment)
# Set the path to your NetLogo instalation
nl_netlogo_path("c:/Program Files/NetLogo 6.0.1/app/") 
```

While using `step_measures` and `run_measures` 
(see [Fire experiments](fire.html)) 
is good enough for aggregate measures, there are cases when we need to 
"measure" each agent individually. 

Example below is using 
Netlogo Segregation model (Wilensky, 1997) from NetLogo model library to
demonstrate "agents" measures.

<aside>
Wilensky, U. (1997). NetLogo
[Segregation model](http://ccl.northwestern.edu/netlogo/models/Segregation). 
Center for Connected Learning and Computer
</aside>

To get data about agents use `agents_after` argument 
with a list of agents variables and type of agent (turtles in this example).


```{r segregModel, title = "Define the experiment"}
experiment <- nl_experiment(
  model_file = "models/Sample Models/Social Science/Segregation.nlogo", 
  while_condition = "count turtles with [not happy?] > 0",
  param_values = list(
    percent_similar_wanted = c(30, 50, 70)
  ),
  mapping = c(
    percent_similar_wanted = "%-similar-wanted"
  ),
  agents_after = list(
    individuals = agent_set(
      vars = c("who", "xcor", "ycor", group = "color", happy = "happy?"), 
      agents = "turtles")  
  ),
  random_seed = 1
)
```
<aside>
Note that turtle variable "color" is mapped to group variable 
</aside>

```{r segregRun, title = "Run the experiment", cache=TRUE}
result <- nl_run(experiment)
```


The data about individual agents are now stored in `result$agents_after$individuals`.
To join the data with the values from parameter sets use `nl_get_result` function.

```{r segregDat, title = "Get data"}
dat <- nl_get_result(result, type = "agents_after", sub_type = "individuals")
```


```{r segregPlot, title = "Plot", fig.height=3, fig.cap="Segregation results for different values of %-similar-wanted"}
library(ggplot2)
dat$group <- factor(dat$group, labels = c("A", "B"))
ggplot(dat, aes(x = xcor, y = ycor, fill = group)) +
  geom_raster() +
  coord_fixed() +
  facet_grid( ~ percent_similar_wanted, labeller = label_both) +
  scale_fill_manual(values = c("cadetblue4", "gray" )) +
  theme_minimal() 
```

## See also

[Network](network.html) example demonstrates how to read a network structure
from NetLogo turtles and links.

[Traffic](traffic.html) example demonstrates how to collect values from
 turtles per each time step.
 
[DLA](dla.html) example demonstrates how to read patches and their variables.

[Ants](ants.html) example demonstrates simple parameter sets 
definition and parameter mapping.

<asideclose>
Get [rmarkdown source](`r knitr::current_input()`) of this page.
</asideclose>
