Wednesday, February 19, 2014

Just an update on R coding

I'm teaching an introduction to political analysis course at UNLV this spring.  I have gone out on a limb and am teaching the students R instead of STATA or SPSS.  I am more familiar with STATA, but do my network analysis work in R.  I am trying to become more proficient.  I had a problem with a project I am working on - trying to count the number of rivalry ties that a state has in any given year. Normally I would do this in STATA, but I decided to give it a whirl in R.  After two hours and numerous "googlings" I have produced the code to give me the count for each year of my data.  The code looks like this:


for(i in 1816:2010){
  fp <- file.path("network", paste("net", i, ".txt", sep = ""))
  outcount <- file.path("count", paste("count", i, ".csv", sep=""))
 
  file <- read.table(fp)
  #sum row - this is the number of out ties by a state
  count.row <-rowSums(file, na.rm=FALSE, dims=1)
  count.col <- colSums(file, na.rm=FALSE, dims=1)
  comb.ties <- cbind(count.row, count.col)
  total.ties <- rowSums(comb.ties, na.rm=FALSE, dims=1)
  write.csv(total.ties, file= outcount, row.names = TRUE)  
}
Created by Pretty R at inside-R.org

The data come from text files with a network matrix (sociomatrix) for the states involved in the international system.  I use these to examine network characteristics in other contexts.  Here, I have just used them as matrices and have used the summing features to get both the outgoing ties, states that identify others as rivals, and in ties, those that identify the state as rivals.  These are combined and summed for a total.  The total is then exported to a CSV file that can be used in other contexts.  It's blunt force, and perhaps inelegant, but it's mine!

No comments:

Post a Comment