# Konstantin Kashin

Institute for Quantitative Social Science, Harvard University

Konstantin Kashin is a Fellow at the Institute for Quantitative Social Science at Harvard University and will be joining Facebook's Core Data Science group in September 2015. Konstantin develops new statistical methods for diverse applications in the social sciences, with a focus on causal inference, text as data, and Bayesian forecasting. He holds a PhD in Political Science and an AM in Statistics from Harvard University.

## DAGs in R

| Tags: R causal inference

Following up on the previous post, another way to construct DAGs is using R. I think the igraph package is one of the customizable ways to do so. This is a powerful package designed for the visualization and analysis of networks and offers much more functionality than you will use for DAGs.

The R equivalent to the instrumental variables DAG constructed in TeX in the preceding post is the following:

To construct this in R, first you want to create an igraph object (with directed edges) as follows:

g1 <- graph.formula(Z--+T, T--+Y,U--+T, U--+Y, U--+Z, Z--+Y)


If you just view the g1 object (by running g1), you will see the following:

IGRAPH DN-- 4 6 --
+ attr: name (v/c)


This denotes that this is a directed named (DN) network with 4 vertices (nodes) and 6 edges. The names of the vertices are stored as an attribute (and correspond to the variable names: Z, T, U, Y). Note that we can access the vertex name attribute as V(g1)$name. Running this will help us identify the order in which the vertices were entered into the igraph object: V(g1)$name
[1] "Z" "A" "Y" "U"


To give the vertices custom attributes:

V(g1)$label <- V(g1)$name
V(g1)$color <- c(rep("black",3),"white") V(g1)$size <- 7
V(g1)$label.cex <- 1.5 V(g1)$label.dist <- 2
V(g1)$label.color <- "black"  Now the edges (first see the edge sequence by running E(g1)): E(g1)$color <- "black"
E(g1)$color[2] <- E(g1)$color[4] <- "red"
E(g1)$lty <- c(1,2,1,2,1,1) E(g1)$label <- c(NA,"X",NA,"X",NA,NA)
E(g1)$label.color <- "red" E(g1)$label.cex <- 1.5


If you run plot(g1) now, you will note that the igraph library automatically arranges the vertices. To manually override this arrangement, run the following command:

tkplot(g1)


This opens an interactive graphing screen that allows you to manually move around the vertices and arrange them as you want. Now, while leaving the popup window open, extract the new coordinates for the vertices as:

coord.g1 <- tkplot.getcoords(1)


(Note that the 1 refers to the number of the interactive window – this one was the first I opened in this R session).

Now, pass these coordinates to the plotting of the igraph object (along with moving around the label location relative to the vertices):

plot(g1, layout=coord.g1,vertex.label.degree=c(pi,pi/2, 0, -pi/2)