Author Archive

Drop list elements if

I am doing a simulation in R that generates a list of simulated data objects and then simulates emergent behavior on them. Unfortunately, it chokes on “data” meeting a certain set of conditions and so I need to kick data like that from the list before running it. This is kind of hard to do as if you delete a list element you mess up the indexing since when you kick a list element the list is now shorter. My solution is to create a vector of dummies flagging which list elements to kick by indexing in ascending order, but then actually kick list elements in descending order. Note that if the length of the list is used elsewhere in your code that you’ll need to update it after running it.

FWIW, the substantive issue in my case is diffusion where some of the networks contain isolates, which doesn’t work in the region of parameter space which assumes all diffusion occurs through the network. In my case, deleting these networks is a conservative assumption.

Capture

Apologies for posting the code as a screenshot but WordPress seems to really hate recursive loops, regardless of whether I use sourcecode or pre tags.

 

 

Advertisements

April 5, 2019 at 2:43 pm Leave a comment

EU migrants

| Gabriel |

Yesterday the Guardian published a list of 34,361 migrants who had died attempting to reach or settle within Europe. (The list is originally from United for Intercultural Action).  The modal cause of death is shipwreck, but the list also includes suicides, homicides, terrestrial accidents, etc. I was curious as to the timeline as to when these deaths occurred so I converted the PDF list to a csv and made a graph and a few tables.

The graph is noisy, but nonetheless a few trends jump out.

Deaths rose slowly through the 1990s until 2006 and 2007 then dropped. Presumably this reflects declining labor demand in the EU. There is an isolated jump in 2009, but deaths are low in 2008 and 2010.

Deaths spike sharply in 2011, especially March of that year, which coincides with regime collapse in Libya. (Since 2004 Gaddafi had been suppressing migrant traffic as part of a secret deal with Italy). Deaths were low again by late 2011.

The dog that didn’t bark is that migrant deaths were relatively low throughout 2012 and 2013, notwithstanding the Syrian Civil War.

In October 2013 there was a major shipwreck, after which the Italians launched Operation Mare Nostrum, in which the Italian Navy would rescue floundering vessels. For the first few months this seems to have been successful as a humanitarian effort, but  eventually the Peltzman Effect took to sea and deaths skyrocketed in the summer of 2014. After this spike (and the budget strain created by the operation), the Italians cancelled Operation Mare Nostrum and deaths decreased briefly.

Operation Triton replaced Mare Nostrum, which was a) a pan-European effort and b) less ambitious. The post-Mare Nostrum death lull ended in spring of 2015.

European Union states had widely varying migration policies during 2015, with some enacting restrictionist policies and others pro-migration policies. Although there were many migrant deaths in 2015, they were mostly in the spring. Angela Merkel’s various pro-immigration statements (circa September and October of 2015) do not seem to have yielded a moral hazard effect on deaths, perhaps because this was almost simultaneous with the EU getting an agreement with Turkey to obstruct migrant flows. In any case, migrant deaths were relatively low in the last quarter of 2015 and first quarter of 2016. Deaths were very high in March and April of 2016 and overall 2016 was the worst year for deaths in the EU migration crisis.

In 2017 deaths declined back to 2015 levels, being high in both years but not as high as the peak year of 2016. It is too early to describe trends for 2018 but deaths in the first quarter of 2018 are lower than those of any quarter in 2017.

migrants

*http://unitedagainstrefugeedeaths.eu/wp-content/uploads/2014/06/ListofDeathsActual.pdf
*ran PDF through pdf/csv translator then stripped out lines with regex for lines not starting w digit
cd "C:\Users\gabri\Dropbox\Documents\codeandculture\eumigrants\"
import delimited ListofDeathsActual.csv, varnames(1) clear
keep if regexm(found,"^[0-9]")
drop v7-v30
gen date = date(found,"DMY",2019)
format date %td
gen n=real(number)
sum n
gen week=wofd(date)
format week %tw
gen month=mofd(date)
format month %tm
gen year=yofd(date)
save eudeaths.dta, replace
table month, c(sum n)
table year, c(sum n)
collapse (sum) n, by(week)
sort week
lab var n "deaths"
twoway (line n week)
graph export migrants.png, replace

June 21, 2018 at 4:11 pm 4 comments

Networks Reading List

| Gabriel |

In response to my review of Ferguson’s Square and the Tower, several people have asked me what to read to get a good introduction to social networks. First of all, Part I of Ferguson’s book is actually pretty good. I meant it when I said in the review that it’s a pretty good intro to social networks and in my first draft I went through and enumerated all the concepts he covers besides betweenness and hierarchy being just a tree network. Here’s the list: degree, sociometry, citation networks, homophily, triadic closure, clustering coefficients, mean path length, small worlds, weak ties as bridges, structural holes, network externalities, social influence, opinion leadership, the Matthew Effect, scale free networks, random graph networks, and lattices. While I would also cover Bonacich centrality / dependence and alpha centrality / status, that’s a very good list of topics and Ferguson does it well. I listed all my issues with the book (basically 1) he’s not good on history/anthropology prior to the early modern era and 2) there’s a lot of conceptual slippage between civil society and social networks as a sort of complement (in the set theory sense) to the state and other hierarchies. However it’s a very well written book that covers a lot of history, including some great historical network studies and the theory section of the book is a good intro to SNA for the non-specialist.

Anyway, so what else would I recommend as the best things to get started with for understanding networks, especially for the non-sociologist.

Well obviously, I wrote the best short and fun introduction.

dylan

My analysis of combat events in the Iliad is how I teach undergraduates in economic sociology and they like it. (Gated Contexts version with great typesetting and art, ungated SocArxiv version with the raw data and code). This very short and informal paper introduces basic concepts like visualization and nodes vs edges as well as showing the difference between degree centrality (raw connections), betweenness centrality (connections that hold the whole system together), and alpha centrality (top of the pecking order).

Social networks is as much a method as it is a body of theory so it can be really helpful to play with some virtual tinker toys to get a tactile sense of how it works, speed it up, slow it down, etc. For this there’s nothing better than playing around in NetLogo. There’s a model library including several network models like “giant component” (Erdos-Renyi random graph), preferential attachment, “small world” (Watts and Strogatz ring lattice with random graph elements), and team assembly. Each model in the library has three tabs. The first shows a visualization that you can slow down or speed up and tweak in parameter space. This is an incredibly user-friendly and intuitive way to grok what parameters are doing and how the algorithm under each model thinks. A second tab provides a well-written summary of the model, along with citations to the primary literature. The third tab provides the raw code, which as you’d expect is a dialect of the Logo language that anyone born in the late 1970s learned in elementary school. I found this language immediately intuitive to read and it only took me two days to write useful code in it, but your mileage may vary. Serious work should probably be done in R (specifically igraph and statnet), but NetLogo is much better for conveying the intuition behind models.

Since this post was inspired by Square and the Tower and my main gripe about that is slippage between civil society and social networks, I should mention that the main way to take a social networks approach to civil society in the literature is to follow Putnam in distinguishing between bridging (links between groups) and bonding (links within groups) social capital. TL;DR is don’t ask the monkey’s paw for your society to have social capital without specifying that you want it to have both kinds.

If you want to get much beyond that, there are some books. For a long time Wasserman and Faust was canonical but it’s now pretty out of date. There are a few newer books that do a good job of it.

The main textbook these days is Matthew O. Jackson’s Social and Economic Networks. It’s kind of ironic that the main textbook is written by an economist, but if Saul of Tsarsus could write a plurality of the New Testament, then I guess an economist can write a canonical textbook on social network analysis. It covers a lot of topics, including very technical ones.

I am a big fan of The Oxford Handbook of Analytical Sociology. Analytical sociology isn’t quite the same thing as social networks or complex systems, but there’s a lot of overlap. Sections I (Foundations) and III (Social Dynamics) cover a lot in social networks and related topics like threshold models. (One of my pet peeves is assuming networks are the only kind of bottom-up social process so I like that OHoAS includes stuff on models with less restrictive assumptions about structure, which is not just a simplifying assumption but sometimes more accurate).

I’m a big fan of John Levi Martin’s Social Structures. The book divides fairly neatly into a first half that deals with somewhat old school social networks approaches to small group social networks (e.g., kinship moieties) and a second half that emphasizes how patronage is a scalable social structure that eventually gets you to the early modern state.

Aside from that, there’s just a whole lot of really interesting journal articles. Bearman, Moody, and Stovel 2004 maps the sexual network of high school students and discover an implicit taboo on dating your ex’s partner’s ex. Smith and Papachristos 2016 look at Al Capone’s network and show that you can’t conflate different types of ties, but neither can you ignore some types, only by taking seriously multiple types of ties as distinct can you understand Prohibition era organized crime. Hedström, Sandell, and Stern 2000 show that the Swedish social democratic party spread much faster than you’d expect because it didn’t just go from county to county, but jumped across the country with traveling activists, which is effectively an empirical demonstration of a theoretical model from Watts and Strogatz 1998.

February 6, 2018 at 12:24 pm 1 comment

Blue upon blue

| Gabriel |

On Twitter, Dan Lavoie observed that Democrats got more votes for Congress but Republicans got more seats. One complication is that some states effectively had a Democratic run-off, not a traditional general. It is certainly true that most Californians wanted a Democratic senator, but not 100%, which is what the vote shows as the general was between Harris and Sanchez, both Democrats. That aside though, there’s a more basic issue which is that Democrats are just more geographically concentrated than Republicans.

Very few places with appreciable numbers of people are as Republican as New York or San Francisco are Democratic (ie, about 85%). Among counties with at least 150,000 votes cast, in 2004 only two suburbs of Dallas (Collin County and Denton County) voted over 70%. In 2008 and 2012 only Montgomery County (a Houston suburb) and Utah county (Provo, Utah) were this Republican. By contrast, in 2004 sixteen large counties voted at least 70% Democratic and 25 counties swung deep blue for both of Obama’s elections. A lot of big cities that we think of as Republican are really slightly reddish purple. For instance, in 2004 Harris county (Houston, Texas) went 55% for George W Bush and Dallas was a tie. In 2012 Mitt Romney got 58% in Salt Lake. The suburbs of these places can be pretty red, but as a rule these suburbs are not nearly as red as San Francisco is blue, not very populated, or both.

I think the best way to look at the big picture is to plot the density of Democratic vote shares by county, weighted by county population. Conceptually, this shows you the exposure of voters to red or blue counties.

Update
At Charlie Seguin’s suggestion, I added a dozen lines of code to the end to check the difference between the popular vote and what you’d get if you treated each county as winner-take-all then aggregated up weighted by county size. Doing so it looks like treating counties as winner-take-all gives you a cumulative advantage effect for the popular vote winner. Here’s a table summarizing the Democratic popular vote versus the Democratic vote treating counties as a sort of electoral college.
Popular vote Electoral counties
2004 48.26057 0.4243547
2008 52.96152 0.6004451
2012 51.09047 0.5329050
2016 50.12623 0.5129522

elect.png

setwd('C:/Users/gabri/Dropbox/Documents/codeandculture/blueonblue')
elections <- read.csv('https://raw.githubusercontent.com/helloworlddata/us-presidential-election-county-results/master/data/us-presidential-election-county-results-2004-through-2012.csv')
elections$bluecounty <- ifelse(elections$pct_dem>50, 1, 0)

elect04 <- elections[(elections$year==2004 & elections$vote_total>0),]
elect04$weight <- elect04$vote_total/sum(elect04$vote_total)
dens04 <- density(elect04$pct_dem, weights = elect04$weight)
png(filename="elect04.png", width=600, height=600)
plot(dens04, main='2004 Democratic vote, weighted by population', ylab = 'Density, weighted by county population', xlab = "Democratic share of vote")
dev.off()

elect08 <- elections[(elections$year==2008 & elections$vote_total>0),]
elect08$weight <- elect08$vote_total/sum(elect08$vote_total)
dens08 <- density(elect08$pct_dem, weights = elect08$weight)
png(filename="elect08.png", width=600, height=600)
plot(dens08, main='2008 Democratic vote, weighted by population', ylab = 'Density, weighted by county population', xlab = "Democratic share of vote")
dev.off()

elect12 <- elections[(elections$year==2012 & elections$vote_total>0),]
elect12$weight <- elect12$vote_total/sum(elect12$vote_total)
dens12 <- density(elect12$pct_dem, weights = elect12$weight)
png(filename="elect12.png", width=600, height=600)
plot(dens12, main='2012 Democratic vote, weighted by population', ylab = 'Density, weighted by county population', xlab = "Democratic share of vote")
dev.off()

elect16 <- read.csv('http://www-personal.umich.edu/~mejn/election/2016/countyresults.csv')
elect16$sumvotes <- elect16$TRUMP+elect16$CLINTON
elect16$clintonshare <- 100*elect16$CLINTON / (elect16$TRUMP+elect16$CLINTON)
elect16$weight <- elect16$sumvotes / sum(elect16$sumvotes)
elect16$bluecounty <- ifelse(elect16$clintonshare>50, 1, 0)
dens16 <- density(elect16$clintonshare, weights = elect16$weight)
png(filename = "elect16.png", width=600, height=600)
plot(dens16, main='2016 Democratic vote, weighted by population', ylab = 'Density, weighted by county population', xlab = "Democratic share of vote")
dev.off()

png(filename = "elect.png", width=600, height=600)
plot(dens04, main='Democratic vote, weighted by population', ylab = 'Density, weighted by county population', xlab = "Democratic share of vote", col="blue")
lines(dens08)
lines(dens12)
lines(dens16)
dev.off()


m <- matrix(1:8,ncol=2,byrow = TRUE)
colnames(m) <- c("Popular vote","Electoral counties")
rownames(m) <- c("2004","2008","2012","2016")
m[1,1] <- weighted.mean(elect04$pct_dem,elect04$weight)
m[1,2] <- weighted.mean(as.numeric(elect04$bluecounty),elect04$weight)
m[2,1] <- weighted.mean(elect08$pct_dem,elect08$weight)
m[2,2] <- weighted.mean(as.numeric(elect08$bluecounty),elect08$weight)
m[3,1] <- weighted.mean(elect12$pct_dem,elect12$weight)
m[3,2] <- weighted.mean(as.numeric(elect12$bluecounty),elect12$weight)
m[4,1] <- weighted.mean(elect16$clintonshare,elect16$weight)
m[4,2] <- weighted.mean(as.numeric(elect16$bluecounty),elect16$weight)
m

 

November 9, 2017 at 11:24 am

Strange Things Are Afoot at the IMDb

| Gabriel |

I was helping a friend check something on IMDb for a paper and so we went to the URL that gives you the raw data. We found it’s in a completely different format than it was last time I checked, about a year ago.

The old data will be available until November 2017. I suggest you grab a complete copy while you still can.

Good news: The data is in a much simpler format, being six wide tables that are tab-separated row/column text files. You’ll no longer need my Perl scripts to convert them from a few dozen files that are a weird mish mash of field-tagged format and the weirdest tab-delimited text you’ve ever seen. Good riddance.

Bad news: It’s hard to use. S3 is designed for developers not end users. You could download the old version with Chrome or “curl” from the command line. The new version requires you to create an S3 account and as best I can tell, there’s no way to just use the S3 web interface to get it. There is sample Java code, but it requires supplying your account credentials which gives me cold sweat flashbacks to when Twitter changed its API and my R scrape broke. Anyway, bottom line being you’ll probably need IT to help you with this.

Really bad news: A lot of the files are gone. There’s no country by country release dates, no box offices, no plot keywords, there are only up to three genres, no distributor or production company, etc. These are all things I’ve used in publications.

September 8, 2017 at 2:29 pm 3 comments

The more things change

| Gabriel |

I just listened to a podcast conversation [transcript / audio] between Tyler Cowen and Ben Sasse and very much enjoyed it but was bothered by one of the senator’s laugh lines, “Turned out sex was really similar in most centuries.”* Now in a sense this is obviously true since any culture in which sex lost a certain aspect would only last one generation, and indeed this has happened. But there is still a lot of variation within the scope condition that in pretty much all times and places, sex is procreative at least some of the time. What kinds of sex one has varies enormously over time, as does with what kinds of and how many people. We can see this over big periods of history and within living memory in our own culture. My discussion will be necessarily detailed, but not prurient.

Dover’s Greek Homosexuality uses detailed interpretation of comedies, legal speeches, pornographic pottery, and similar sources to provide a thorough picture of sexuality in 4th and 5th c BCE Greece, especially among Athenian upper class men, but not limited just to the idiosyncratic and often idealized views of philosophers. There were two big differences with our culture, the most obvious being that with whom you had sex varied over the life course and the less obvious but equally important one being that what role you played was equally important as with whom you played it. An aristocratic Athenian male would typically be an eromenos (“beloved” or passive homosexual) in his late teens and when he reached full maturity would be an erastes (“lover” or active homosexual) but also get married to a woman. As long as you stuck to this life course trajectory, no money changed hands, and the eromenos had love but not lust for his erastes, the relationship was honorable. However for someone to remain an eromenos into full maturity was scandalous and bearded men who continued to accept passive sexual roles were stigmatized. Interestingly, what exactly is the action that occurs between active and passive varies enormously based on source, with philosophers downplaying sex entirely, pornographic pottery suggesting intercrural sex, and Aristophanes joking about anal intercourse (e.g., the best food for a dung beetle).

One thing the sources seem to agree on is that fellatio generally did not occur among Greek men. Dover argues that the avoidance of fellatio, avoidance of prostitution, and age separation of partners all served the purpose of avoiding hubris (assault that degrades status) otherwise implied by one male citizen penetrating another. Generally, our culture’s ubiquity of fellatio, and especially our common assumption that it is less intimate than vaginal intercourse, is exceptional across cultures. This is not only an issue of Greece, fellatio was exceptionally rare in 18th c elite French prostitution (although anal sex was common) and in early 20th c New York city. Interestingly, Dover notes that the women of Lesbos were legendary in Greek culture for heterosexual fellatio. While our culture derives our word for gay women from that island, largely through it being the home of Sappho, the cultural meaning in antiquity was of fellatrix, though the two meanings made sense in the Greek mind as relating to women who were especially open to sex of many varieties. This sounds bizarre to us, but as I’ll describe in a bit, this reflects emerging practice in our own culture.

For changes in recent decades, we do not need to rely on measuring the angles of penetration depicted on a kylix or on epithets in old comedy but can go by systematic survey data.** The main finding of Laumann et al’s 1994 Sex in America study was that sex was much more focused on monogamy, marriage, and vaginal intercourse than anyone expected based on Kinsey (who relied on convenience sampling) or popular culture. However things have changed a lot in the last two decades and in ways much more profound than that my undergrads don’t like rock music. The National Survey of Family Growth 2002-2013 replicates most of the research questions of Laumann et al and found that sex had gotten much more complicated since the early 1990s.  One major finding is a substantial rise in same sex intercourse. Women born from 1966-1974 are half as likely to have had same sex intercourse as women born from 1985-1995. In contrast to ancient Athens, this rise in same sex intercourse is limited to women (and the base rate is much higher), but as in ancient Greece, it is mostly an issue of youthful experimentation that is complementary to heterosexual practice and on the margin women self-identify as straight or bi, not lesbian. Chandra et al’s analysis of the same data showed a corollary that echos ancient stereotypes of Lesbians, which is that female experience with same sex partners is positively correlated with lifetime number of male partners. In addition, Chandra et al found that heterosexual anal intercourse is rising substantially, with about 30% of women aged 18-44 in 2002 having experienced it, or almost double what Laumann et al found twenty years earlier. This likely reflects influence from pornography, as does the almost universal (~85%) adoption of pubic grooming among women under thirty. However, again, this reflects ancient trends as ancient Greek women would singe off pubic hair and indeed the punishment for a male adulterer was to be symbolically feminized through pubic depilation and penetration with a radish.

* Sasse elaborated that he meant that in all times and places sex serves a mix of recreation, procreation, and pair-bonding and I think he’s right about that.

** I am not relying on pornography production or usage data as I strongly suspect that pornography follows a zero-inflated over-dispersed count distribution and thus consumption data, especially that showing that pornography is increasingly bizarre, is mostly informative about a relatively small minority of intensive users.

July 3, 2017 at 10:38 am 11 comments

Medicaid and mortality

| Gabriel |

This morning Spotted Toad picked up on the point in Quinones that a lot of pill mills were funded through Medicaid fraud and so he used Medicaid expansion under Obamacare to see if this led to greater drug overdoses in Medicaid expansion states. In fact he found that in the time since the Medicaid expansion, states that participated in the expansion had faster growth in overdose deaths than states that refused Medicaid expansion. That’s interesting, but I never want to base a trend on just two time points. (FWIW, Toad was analyzing the data as the CDC presents it — the analysis below requires a lot more queries). So I queried the CDC data in more granular detail to check if the trend started with Medicaid expansion. (saved query link, just iterate over year to get annual state-level OD deaths).

As it turns out, I was able to replicate Toad’s finding that Medicaid expansion states (blue) have higher rates and faster growth in fatal drug overdoses than Medicaid holdout states (red), but the two groups of states diverged starting in 2010, well before states began implementing Obamacare’s Medicaid expansion. So there may be a real difference between Medicaid expansion states (which are generally Democratic) and Medicaid holdout states (which are Republican), and the difference may even be some aspect of health policy, but it wasn’t Obamacare Medicaid expansion as the divergence starts too early. (It’s worth noting that Toad updated his own post with my graph as soon as I sent it to him).

medicaidod

Here is the data in Stata format (which you can reconstruct yourself from a series of CDC queries).

Here is the code

cd "~/Documents/codeandculture/cdcdrugmortality"
*https://wonder.cdc.gov/controller/saved/D76/D11F702


clear
gen state=""
gen year=.
save drugs19992015.dta, replace

forvalues i=1999/2015 {
 disp "`i'"
 insheet using drugs`i'.txt, clear
 append using drugs19992015.dta, force
 recode year .=`i'
 save drugs19992015, replace
}
drop if state==""

desc
sum

insheet using medicaidholdouts.txt, clear
ren v1 state
save medicaidholdouts.dta, replace

use medicaidholdouts, clear
merge 1:m state using drugs19992015
ren _merge medicaidexpansion 
recode medicaidexpansion 2=1 3=0

list state medicaidexpansion if (state=="Texas" | state=="California") & year==2010

save drugs19992015, replace

collapse (sum)deaths population, by (year medicaidexpansion)
gen cruderate= deaths/population
twoway (line cruderate year if medicaidexpansion==1) (line cruderate year if medicaidexpansion==0) , legend(order(1 "Medicaid expansion" 2 "Holdouts")) ytitle(Weighted Crude Rate of Fatal Drug Overdoses)
graph export medicaidod.png, replace

*have a nice day

And here’s my list of Medicaid holdouts:

Alabama
Florida
Georgia
Idaho
Kansas
Mississippi
Missouri
Nebraska
North Carolina
Oklahoma
South Carolina
South Dakota
Tennessee
Texas
Utah
Virginia
Wisconsin
Wyoming

 

March 21, 2017 at 9:16 pm 3 comments

Older Posts