Database Reference
In-Depth Information
For this recipe, I'm going to use the U.S. political campaign inance data from Open Secrets
( http://www.opensecrets.org/ ). You have to register with the site, but once you do that,
the data is free to download. Once you've logged in, look for the Bulk Data link. For this, I
downloaded the cycles tables for the Campaign Finance Data. I unzipped them to the data/
campaign-fin directory. For this recipe, we'll focus on the Political Action Committee (PAC)
data. In this case, we'll just ind the total amount of campaign contributions per candidate.
We'll use several utility functions from the last recipe: lazy-read-csv and ->int .
How to do it…
To use agents, we just need to add a few functions to the ones from the last recipe:
1. The irst pair is get-cid and get-amount . These take a row from the data ile
and return the data ields that we're interested in:
(defn get-cid [row] (nth row 3))
(defn get-amount [row] (->int (nth row 4)))
2.
We'll now add a function that takes those two values and wraps them into a
vector pair:
(defn get-cid-amount [row]
[(get-cid row) (get-amount row)])
3.
Now, we'll need a function that indexes those values in a hash map, adding them:
(defn add-amount-by [m cid amount]
(assoc m cid (+ amount (get m cid 0))))
4. Next, we'll deine a function that reads the data from a ile and accumulates it in an
existing hash map:
(defn read-file-amounts [m filename]
(reduce #(add-amount-by %1 (first %2) (second %2))
m
(map get-cid-amount
(lazy-read-csv filename))))
5.
Finally, we'll need a function to make working with agents easier— force-val .
It takes an agent and uses await to block all of the messages currently in its queue
to be processed. Then it dereferences the agent. This function will allow us to thread
a series of operations on the agents:
(defn force-val
[a]
(await a)
@a)
 
Search WWH ::




Custom Search