Friday, January 2, 2015

Blogging in R

Previous posts have discussed how computers, IT, and open source software have made incredible strides in recent years and how those advances are helpful for infectious disease epidemiology. On that theme, I recently found something very cool, which is illustrated here: This entire post was written in the RStudio IDE using the markdown and knitr packages in R.

Markdown is a text-to-HTML conversion tool that allows conversion of prose into structurally valid XHTML or HTML. Details can be found at http://rmarkdown.rstudio.com and a short tutorial is available at https://support.rstudio.com/hc/en-us/articles/200552086-Using-R-Markdown. knitr is an engine for dynamic report generation with R. It is possible to produce sophisticated documents that include bibliographic referencing and mathematical typesetting using markdown and knitr. Moreover, one can generate documents with embedded chunks of R code in order to display the code itself and/or the output.

As a simple example, below is a word cloud made from searching the Twitter API for tweets containing the terms “vaccine” or “vaccinated” in a 24 hour period. The code is shown first (it could be written better, clearly), followed by the output:

rm(list=ls())

library(twitteR)
library(tm)
library(wordcloud)
library(RColorBrewer)
library(RJSONIO)

#====================================================

path_var <- "~/Dropbox/Docs/Blogs/"
auth_var <- "my_oauth.Rdata" 
load(paste(path_var, auth_var, sep=""))
registerTwitterOAuth(my_oauth)

the_search_term <- "-RT vaccine OR vaccinated"
today <- as.character(Sys.Date())
yesterday <- as.character(as.Date(today) - 1)

max_tweets <- 300 
the_filename <- paste(path_var, "twitter_", today, ".csv", sep="")

the_search <- searchTwitter(searchString=the_search_term, 
                            n=max_tweets, 
                            since = yesterday, 
                            until = today)
  
tweets_df <- twListToDF(the_search)
write.csv(tweets_df, file=the_filename)
search_text = sapply(the_search, function(x) x$getText())
search_corpus = Corpus(VectorSource(search_text))

tdm <- TermDocumentMatrix(
  search_corpus,
  control=list(
    removePunctuation=TRUE,
    stopwords=c("amp", "vaccine", "vaccinated", 
                  stopwords("english")), 
    removeNumbers=TRUE, 
    tolower=TRUE)
) # Note we do not display the search terms in the cloud 

m <- as.matrix(tdm)
word_freqs <- sort(rowSums(m), decreasing=TRUE)  
dm <- data.frame(word=names(word_freqs), freq=word_freqs)
layout(matrix(c(1, 2), nrow=2), heights=c(1, 4))
par(mar=rep(0, 4))
plot.new()
fh <- paste("Twitter search API, ", 
            length(tweets_df[,1]), " tweets returned, ", 
            today, sep="")
text(x=0.5, y=0.5, fh)
wordcloud(dm$word, dm$freq, min.freq=5, 
          random.order = FALSE, 
          random.color=FALSE, 
          max.words=Inf, colors = brewer.pal(8, "Dark2"))

The user can control whether the R code appears in the document or not.

This blog was “knitted” into HTML with a single click, and the resulting HTML code was pasted into the blogspot composition tool. A very small amount of editing of this code was needed to make it work on the blogspot.com platform (though the R code is supposed to be depicted in a gray box, so there is at least one thing to sort out as a purest). Voila.

Were it necessary to change the code for some reason, say to add a new API search term or update the word cloud for the same search in a week – or even to fix a bug – then the resulting HTML document can be regenerated and the update published, seamlessly. Thus, R has become a method for producing dynamic documents. Imagine the power of working collaboratively with others through an R Markdown document saved in a shared folder (e.g., in Dropbox).

Do I plan on preparing future blogs in R? No -- it’s not a document preparation environment per se, and the other tools at my disposal are more than sufficient. However, if I were writing a blog that updated figures daily, weekly, or monthly based on changing data, or wanted to share fragments of code, say, I probably would use it.

Getting back to epidemiology, the word cloud is interesting. It shows that people are tweeting about the high levels of flu activity (see, e.g., http://www.cdc.gov/flu/) at present, as well as other topics including Ebola, cancer, and fraud. By reviewing the text of the tweets themselves (which is possible by inspecting the object “tweets_df” in R), a better sense of the diversity of conversation surrounding vaccines and vaccination can be had.

Thursday, January 1, 2015

Follow up: An IGY for medicine

File:International Geophysical Year in 1957.Japanese sttamp of 10yen.jpgHappy New Year to all!

A quick follow up to the recent IGY for medicine post. A colleague in Sierra Leone commented about the post that
The pipe dream is actually happening: it's the Ebola response. In many ways, what you suggest for an International Biomedical Year is exactly what's happening now in West Africa. It's an amazing international effort. The sentiment and organizations are definitely present there, though perhaps the coordination could be improved. That said, if the world NGOs and governmental organizations collaborated like they are for Ebola on other efforts, though more focused as you suggest on research and treatment, a ton could be accomplished.
There's a very positive thought to begin 2015.

Monday, December 29, 2014

Closing the loop on raw milk legislation

Earlier this year I blogged several times about raw milk and the movement advocating drinking it. One of those posts mentioned the Milk Freedom Act of 2014, a bill introduced by Rep. Thomas Massie of Kentucky, which, if passed, would have
Prohibit[ed] a federal department, agency, or court from taking any action that would prohibit, regulate, or otherwise restrict the interstate traffic of milk or a milk product that is unpasteurized and packaged for direct human consumption if such action is based solely upon a determination that because the milk or milk product is unpasteurized it is adulterated, misbranded, or otherwise in violation of federal law.
Just to circle back and check up on the status of the bill, it seems to have gone nowhere. The only echoes that came up in a quick Google search were comments attributed to Massie at a meeting called the "Food Freedom Fest" in September. The comments appear on a food rights and raw milk blog by David Gumpert:
U.S. Congressman Thomas Massie . . . was pessimistic about the chances of actually passing anything in the House of Representatives. Indeed, it isn’t even likely the legislation will get a hearing. “The dairy industry went apoplectic when we introduced the legislation,” he said. “My wife said she didn’t know the lactose industry was so intolerant.” . . . Massie told me after his talk that the best chance to get raw milk legislation through Congress and into law would be as part of some other appropriations bill guaranteed passage. Even that route is a long shot, he said, since not many appropriations bills are likely to get through in the coming year or so.
An alternate interpretation of these comments could be that a bill at odds with the basic tenants of food safety and that would place public health at risk if passed was opposed by corporations who have invested immensely in an infrastructure to deliver safe food. The only way that the bill might get passed is if it piggy backs onto a large appropriations bill, but that probably won't happen because the Congress isn't doing much these days anyway.

So, we can all rest well knowing that the Milk Freedom Act of 2014 will never see the light of day. Thank goodness for a Congress that perfected the art of doing little.

(image source: David Hartley)

Wednesday, December 24, 2014

An IGY for medicine

File:International Geophysical Year in 1957.Japanese sttamp of 10yen.jpgIt's been an interesting first year of blogging, and I want to thank everyone for their helpful input and conversations. It's really been great.

The year 2015 will soon be upon us, bringing with it new opportunities for improving human health across a world fractured with poverty, strife, and war. Robert F Kennedy once said that
There are those that look at things the way they are, and ask why. I dream of things that never were, and ask why not.
This strikes me as an appropriate notion for healthcare and medical research. We should ask "why not?" and "what if?" much, much more often.

A little over 50 years ago an event unfolded that provided both hope for peace and a better understanding of our planet. Lasting for 18 months in 1957 and 1958, it was called the International Geophysical Year (IGY). The idea of an IGY is said to have originated in 1950, at a social gathering in James Van Allen's living room. Someone at the gathering opined that, with the recent development of tools like rockets, radar, and computers, a period of coordinated investigation could make a real impact on understanding the geosphere.

The IGY was thus an attempt to coordinate global research on, and measurements of, the earth, oceans, atmosphere, and sun. The accomplishments of the IGY were legion and included the discovery of the Van Allen radiation belts surrounding the earth; the launch of the first artificial satellites; the charting of ocean depths and ocean currents; and groundbreaking studies of the earth's magnetic field. The IGY required -- and successfully achieved -- international cooperation in a time of significant geopolitical tension. It provided a demonstration of what can be achieved when diverse peoples, who share common and coordinated goals, work together with cutting edge technologies.

Why couldn't we adapt the idea of the IGY and have a future International Biomedical Year, where nations apply tools such as supercomputing, machine learning, and genomic sequencing in a coordinated investigation of the ills plaguing human health? The idea would be to plan collaborative and complementary studies in order to accomplish agreed upon, viable steps toward solutions to important problems.

Admittedly, this is a pipe dream, but why not? What if the world's major government and non-government funding organizations closely coordinated their activities on a truly international, focused initiative? Maybe we could cure one or more cancers, or learn how to cut the incidence of heart disease, or finally understand Alzheimer's disease.

Let's try to ask "why not?" and "what if?" more often in 2015. And may you prosper and be well in the coming year.

(image source: Wikipedia)