Wednesday, December 6, 2017

R Notebook version of my parallel coordinates plots

This is the R Markdown Notebook version of parallel coordinates plots displayed in my post “Playing with microdata”. When you execute code within the notebook, the results appear beneath the code.
For the following code to run, you need to have, (i) downloaded the stata data file “myanmarcs_fy14_datafile_with_dk.dta” from the World Bank site, (ii) after running the step (16) of the code in my previous post “Playing with microdata II: my first parallel coordinates plot”, you have saved the resulting data frame to “pcdf.RData”, and (iii) it exists in the directory for the R Notebook project in RStudio.
load("pcdf.RData")
str(pcdf)
## 'data.frame':    511 obs. of  10 variables:
##  $ row   : int  1 1 1 2 2 2 3 3 3 4 ...
##  $ row0  : int  1 1 1 2 2 2 3 3 3 4 ...
##  $ id    : int  101 101 101 102 102 102 103 103 103 104 ...
##  $ g1r   : Factor w/ 9 levels "Office of the President/ Prime Minster/ Minister",..: NA NA NA 5 5 5 1 1 1 5 ...
##  $ col   : num  18 19 20 7 13 20 7 8 0 7 ...
##  $ r1    : int  18 18 18 7 7 7 7 7 7 7 ...
##  $ r2    : int  19 19 19 13 13 13 8 8 8 13 ...
##  $ r3    : int  20 20 20 20 20 20 NA NA NA 20 ...
##  $ rid   : num  1 2 3 1 2 3 1 2 3 1 ...
##  $ sgcode: Factor w/ 9 levels "1","2","3","4",..: NA NA NA 5 5 5 1 1 1 5 ...
head(pcdf)
##   row row0  id                                            g1r col r1 r2 r3
## 1   1    1 101                                           <NA>  18 18 19 20
## 2   1    1 101                                           <NA>  19 18 19 20
## 3   1    1 101                                           <NA>  20 18 19 20
## 4   2    2 102 Private Sector/ Financial Sector/ Private Bank   7  7 13 20
## 5   2    2 102 Private Sector/ Financial Sector/ Private Bank  13  7 13 20
## 6   2    2 102 Private Sector/ Financial Sector/ Private Bank  20  7 13 20
##   rid sgcode
## 1   1   <NA>
## 2   2   <NA>
## 3   3   <NA>
## 4   1      5
## 5   2      5
## 6   3      5
In my post “Playing with microdata II: my first parallel coordinates plot”, the plot at the bottom of the post was created by running the following code chunk (Note that to get the desired size of plot we use something like “”{r fig.height=6, fig.width=6}“ for a given code chunk):
library(ggplot2)
## Warning: package 'ggplot2' was built under R version 3.3.3
y_levels <- levels(factor(1:35))
ggplot(pcdf, aes(x = rid, y = col, group = row)) +
geom_path(aes(size = NULL, color = sgcode),
alpha = 0.5,
lineend = 'round', linejoin = 'round')+
scale_y_discrete(limits = y_levels, expand = c(0.5, 0)) +
scale_size(breaks = NULL, range=c(1,7))
plot of chunk unnamed-chunk-3
Then I left it there for the reader to try to create plots like the one shown in the last part of my post - "Playing with microdata”.In fact this last graphic consisted of six separate plots which I didn't find an easy way to combine into one page using ggplot2. To dodge this issue I just combined them into a single graphic usig GIMP! I think this is fine for the time being, because my primary purpose is blogging. But for sharing my R code, I should learn to place multiple plots produced by ggplot2 on one page. One promising way here would be to use the multiplot function given in: http://www.cookbook-r.com/Graphs/Multiple_graphs_on_one_page_(ggplot2)/, and there maybe others.
The main idea for improving the above plot would be to select one stakeholder group and plot the lines in this group in one color infront of all other groups in another color. To do so (i) we create Y-axis label to represent codes for development priorities, (ii) we define the order of drawing two groups of lines, (iii) and for the readability of the plots create legends for the line colors with text wrapping, and (iv) add appropriate axis labels and headings.

Create Y-axis labels

# create data frame of response codes to use with ggplot
YL <- data.frame(A=as.character(rep("a2_",35)), n=as.character(seq(1,35,1)))
q <- paste(YL$A,YL$n,sep="")
YL$rcode <- factor(q,levels=q)
head(YL)
##     A n rcode
## 1 a2_ 1  a2_1
## 2 a2_ 2  a2_2
## 3 a2_ 3  a2_3
## 4 a2_ 4  a2_4
## 5 a2_ 5  a2_5
## 6 a2_ 6  a2_6

Create StakeHolder group names with text wrapping

pcdf$SGname <- gsub("/","/ \n",pcdf$g1r)
sgn <- gsub("/","/ \n", levels(pcdf$g1r))
pcdf$SGname <- factor(pcdf$SGname, levels= sgn)
head(pcdf$SGname)
## [1] <NA>                                                
## [2] <NA>                                                
## [3] <NA>                                                
## [4] Private Sector/ \n Financial Sector/ \n Private Bank
## [5] Private Sector/ \n Financial Sector/ \n Private Bank
## [6] Private Sector/ \n Financial Sector/ \n Private Bank
## 9 Levels: Office of the President/ \n Prime Minster/ \n Minister ...

Create new variables in which one stakeholder group name is preserved and other groups are collapsed into “All Others”

pcdf$SG_1 <- ifelse(as.integer(pcdf$g1r) == 1,
    levels(pcdf$SGname)[1], "All Others")
pcdf$SG_2 <- ifelse(as.integer(pcdf$g1r) == 2,
     levels(pcdf$SGname)[2], "All Others")
pcdf$SG_3 <- ifelse(as.integer(pcdf$g1r) == 3,
    levels(pcdf$SGname)[3],
    "All Others")
pcdf$SG_5 <- ifelse(as.integer(pcdf$g1r) == 5,
    levels(pcdf$SGname)[5],
    "All Others")
pcdf$SG_6 <- ifelse(as.integer(pcdf$g1r) == 6,
    levels(pcdf$SGname)[6], "All Others")
pcdf$SG_7 <- ifelse(as.integer(pcdf$g1r) == 7,
    levels(pcdf$SGname)[7], "All Others")
head(pcdf)
##   row row0  id                                            g1r col r1 r2 r3
## 1   1    1 101                                           <NA>  18 18 19 20
## 2   1    1 101                                           <NA>  19 18 19 20
## 3   1    1 101                                           <NA>  20 18 19 20
## 4   2    2 102 Private Sector/ Financial Sector/ Private Bank   7  7 13 20
## 5   2    2 102 Private Sector/ Financial Sector/ Private Bank  13  7 13 20
## 6   2    2 102 Private Sector/ Financial Sector/ Private Bank  20  7 13 20
##   rid sgcode                                               SGname
## 1   1   <NA>                                                 <NA>
## 2   2   <NA>                                                 <NA>
## 3   3   <NA>                                                 <NA>
## 4   1      5 Private Sector/ \n Financial Sector/ \n Private Bank
## 5   2      5 Private Sector/ \n Financial Sector/ \n Private Bank
## 6   3      5 Private Sector/ \n Financial Sector/ \n Private Bank
##         SG_1       SG_2       SG_3
## 1       <NA>       <NA>       <NA>
## 2       <NA>       <NA>       <NA>
## 3       <NA>       <NA>       <NA>
## 4 All Others All Others All Others
## 5 All Others All Others All Others
## 6 All Others All Others All Others
##                                                   SG_5       SG_6
## 1                                                 <NA>       <NA>
## 2                                                 <NA>       <NA>
## 3                                                 <NA>       <NA>
## 4 Private Sector/ \n Financial Sector/ \n Private Bank All Others
## 5 Private Sector/ \n Financial Sector/ \n Private Bank All Others
## 6 Private Sector/ \n Financial Sector/ \n Private Bank All Others
##         SG_7
## 1       <NA>
## 2       <NA>
## 3       <NA>
## 4 All Others
## 5 All Others
## 6 All Others
# convert to factors
pcdf[,12:17] <- lapply(pcdf[,12:17], as.factor)
# change levels of factors
pcdf[,12] <- relevel(pcdf[,12], ref=levels(pcdf[,12])[2])
pcdf[,13] <- relevel(pcdf[,13], ref=levels(pcdf[,13])[2])
pcdf[,14] <- relevel(pcdf[,14], ref=levels(pcdf[,14])[2])
pcdf[,15] <- relevel(pcdf[,15], ref=levels(pcdf[,15])[2])
pcdf[,16] <- relevel(pcdf[,16], ref=levels(pcdf[,16])[2])
pcdf[,17] <- relevel(pcdf[,17], ref=levels(pcdf[,17])[2])
str(pcdf)
## 'data.frame':    511 obs. of  17 variables:
##  $ row   : int  1 1 1 2 2 2 3 3 3 4 ...
##  $ row0  : int  1 1 1 2 2 2 3 3 3 4 ...
##  $ id    : int  101 101 101 102 102 102 103 103 103 104 ...
##  $ g1r   : Factor w/ 9 levels "Office of the President/ Prime Minster/ Minister",..: NA NA NA 5 5 5 1 1 1 5 ...
##  $ col   : num  18 19 20 7 13 20 7 8 0 7 ...
##  $ r1    : int  18 18 18 7 7 7 7 7 7 7 ...
##  $ r2    : int  19 19 19 13 13 13 8 8 8 13 ...
##  $ r3    : int  20 20 20 20 20 20 NA NA NA 20 ...
##  $ rid   : num  1 2 3 1 2 3 1 2 3 1 ...
##  $ sgcode: Factor w/ 9 levels "1","2","3","4",..: NA NA NA 5 5 5 1 1 1 5 ...
##  $ SGname: Factor w/ 9 levels "Office of the President/ \n Prime Minster/ \n Minister",..: NA NA NA 5 5 5 1 1 1 5 ...
##  $ SG_1  : Factor w/ 2 levels "Office of the President/ \n Prime Minster/ \n Minister",..: NA NA NA 2 2 2 1 1 1 2 ...
##  $ SG_2  : Factor w/ 2 levels "Office of Parliamentarian",..: NA NA NA 2 2 2 2 2 2 2 ...
##  $ SG_3  : Factor w/ 2 levels "Employee of a Ministry/ \n PMU/ \n Consultant on WBG project",..: NA NA NA 2 2 2 2 2 2 2 ...
##  $ SG_5  : Factor w/ 2 levels "Private Sector/ \n Financial Sector/ \n Private Bank",..: NA NA NA 1 1 1 2 2 2 1 ...
##  $ SG_6  : Factor w/ 2 levels "CSO","All Others": NA NA NA 2 2 2 2 2 2 2 ...
##  $ SG_7  : Factor w/ 2 levels "Media","All Others": NA NA NA 2 2 2 2 2 2 2 ...

Plot by all stakeholder groups

# plot responses for development priorities for all stakeholder groups
y_levels <- levels(YL$rcode)
ggplot(pcdf, aes(x = rid, 
        y = col, group=row))+ 
        labs(title = "General Issues Facing Myanmar:", 
            subtitle = "Development Priority")+
        xlab("Three responses")+
        ylab("Response code")+
        geom_path(aes(color = SGname), lineend='round',
            linejoin='round', size=0)+
            scale_y_discrete(limits = y_levels)+
            scale_size(breaks = NULL, range = c(1, 35))
plot of chunk unnamed-chunk-9

Define the order of drawing the groups of lines

The idea is from “ggplot2: Determining the order in which lines are drawn”: http://blog.mckuhn.de/2011/08/ggplot2-determining-order-in-which.html.
pcdf$o1 <- as.factor(apply(format(pcdf[,c("SG_1", "row")]), 1, paste, collapse=" "))
pcdf$o2 <- as.factor(apply(format(pcdf[,c("SG_2", "row")]), 1, paste, collapse=" "))
pcdf$o3 <- as.factor(apply(format(pcdf[,c("SG_3", "row")]), 1, paste, collapse=" "))
pcdf$o5 <- as.factor(apply(format(pcdf[,c("SG_5", "row")]), 1, paste, collapse=" "))
pcdf$o6 <- as.factor(apply(format(pcdf[,c("SG_6", "row")]), 1, paste, collapse=" "))
pcdf$o7 <- as.factor(apply(format(pcdf[,c("SG_7", "row")]), 1, paste, collapse=" "))
Previous plot shows that some respondents didn't identify the SG they belong.
So rows for pcdf$g1r with NA's have to be dropped from the data frame.
pcdf.1 <- pcdf[!is.na(pcdf$g1r),]
nrow(pcdf.1)
## [1] 445

Create plots with emphasis on a particular stakeholder group

Two plots were drawn for Stakeholder Groups SG_3 and SG_7 with headings, labels for axes, thicker line size, front line color blue and background line color yellow. This is done by using “scale_colour_manual(values=c('blue','yellow'))”. I was happy playing with many combinations of two different colors before I settled with blue and yellow.
Find out what staggering number of colors you could use by “colors()”. To know how ggplot2 define the colors of factors, Q/A such as these may be useful: https://stackoverflow.com/questions/46393082/ggplot2-why-is-color-order-of-geom-line-graphs-reversed, and https://stackoverflow.com/questions/9887342/ggplot2-plotting-order-of-factors-within-a-geom.
Legend is placed at the bottom of the plot. Plots for the remaining groups could be drawn by changing the group=, subtitle, and color= appropriately.
# for SG_3
plot <- ggplot((pcdf.1), aes(x = rid, 
        y = col, group=o3))+ 
        labs(title = "General Issues Facing Myanmar: \n Development Priority", 
            subtitle = "(Group-3 vs. All Others)")+
        xlab("Three responses")+
        ylab("Response code")+
        geom_path(aes(color = SG_3), lineend='round',
            linejoin='round', size=.8)+
            scale_colour_manual(values=c('blue','yellow'))+
            scale_y_discrete(limits = y_levels)+
            xlim("First","Second", "Third", "(Fourth)")+
            scale_size(breaks = NULL)
        plot + theme(legend.text = element_text(size = 8, hjust = .1, vjust = .1),
        legend.position = "bottom")
plot of chunk unnamed-chunk-12
# for SG_7
plot <- ggplot((pcdf.1), aes(x = rid, 
        y = col, group=o7))+ 
        labs(title = "General Issues Facing Myanmar: \n Development Priority", 
            subtitle = "(Stakeholder Group-7 vs. All Others)")+
        xlab("Three responses")+
        ylab("Response code")+
        geom_path(aes(color = SG_7), lineend='round',
            linejoin='round', size=.8)+
            scale_colour_manual(values=c('blue','yellow'))+
            scale_y_discrete(limits = y_levels)+
            xlim("First","Second", "Third", "(Fourth)")+
        scale_size(breaks = NULL)
        plot + theme(legend.text = element_text(size = 8, hjust = .1, vjust = .1),
        legend.position = "bottom")
plot of chunk unnamed-chunk-13

Confessions of a dumb blogger - IV: reproducible science


As young civil servant recruits, one of us talked about the Communist Manifesto at least once. It was such a long time I couldn't remember who introduced that topic and as usual we weren't that serious. In those days we must have been pretending to be the intelligentsia of the times hotly debating politics, arts, poverty, and science over a few cups of tea offered, almost every afternoon, by an artist friend.

It's forty-plus years since I've heard about another manifesto - A manifesto for reproducible science (NATURE HUMAN BEHAVIOUR 1, 0021 (2017) | DOI: 10.1038/s41562-016-0021). This time without company, peering hard at my laptop screen while sipping through a cup of instant white coffee brought back from Viet Nam by a family friend. This time I was looking through the search results on reproducible research and open science and this time too I was no smarter than the last time I was being exposed to “big” ideas.

Anyway, true to my philosophy of easier done than said, I would skim the related topics starting with Wikipedia or whatever catches my eyes first. When I got a little bit of a feeling of what the field looks like I would start looking for what I could do hands-on. I would say that this is the second step of the celebrated dictum for acquiring knowledge in our Myanmar language—suu-tuu-pyuu. To quote myself from an earlier post:

Learning Machine-Learning (or for that matter Data Mining, or Statistics, or …) is obviously easier said than done. Yet we may approach any kind of learning through a three-step process: စု- တု-ပြု(suu-tuu-pyuu) or accumulate-imitate-create, as we Myanmars used to say. Turning our conventional wisdom upside down, I would now suggest that at least for the accumulation step, it could be easier done than said!

I won't fumble with my own words to say something about open science and reproducible research because that would be quite useless. But I think I could say that what reproducible research, open science, and the like are doing is essentially asking the travelers before us to leave their tracks and stick their notes for a journey we have not done before and for “Which to discover we must travel too” as Rubaiyat puts it:


But shouldn't there be exceptions to “Not one returns to tell us of the Road ” relating to less sublime aspects of our lives? Within the vulgarities of our lives, or more importantly in science, to be really helpful should we not resist our selfish habit to share the fish only for the pot, but hide the spot where we cast our nets (ဟင်းစားဘဲပေးမယ် ကွန်ချက်တော့မပြဘူး)? And I know at least this example from Christopher Gandrud:


He went as far as to let you reproduce the book from its source code! Truly a technological “frying the carp with its own fat”(ငါးကြင်းဆီနဲ့ငါးကြင်းကြော်). The book carries this message:

      1. Reproduce this book
This book practices what it preaches. It can be reproduced. I wrote the
book using the programs and methods that I describe. Full documentation
and source files can be found at the book’s GitHub repository. Feel free to
read and even use (within reason and with attribution, of course) the book’s
source code. You can find it at: https://GitHub.com/christophergandrud/
Rep-Res-Book.

If you can't go as far as Gandrud you could try to imitate him in a small way (I'm veering away from Gandrud because I haven't read him yet). Here's a new facility called R Notebooks added to RStudio in October 2016. The following excerpt from “Why I love R Notebooks” by R Views neatly summarizes what I want to know about the R Notebook and how I could use it:

So I tried to do data science with R Notebook, in order to (i) tell you about the details of creating the parallel coordinates plots shown in my post “Playing with microdata”, (ii) show you the output produced by executing the chunks of code written for that purpose, and (iii) share all those chunks of code in a single, reproducible document.

It went well and the resulting HTML file could be opened in any browser from where you could download the Rmd file:


However, posting of this HTML output to Blogger is not straightforward. On this problem Bart Rogiers, as recently as June of this year, wrote that you need to be an HTML/JavaScript/CSS expert to be able to publish HTML document as a Blogger post without destroying the formatting. His workaround consisted of this workflow: (i) Create your R script (ii) Compile your notebook (iii) Get self-contained html body code (without images) (iv) Modify image urls (v) Further modify HTML if necessary (vi) Publish.

Luckily, Kyle's workaround that I used for my previous post “Confessions of dumb blogger - II” still works, but not as good as Rogiers would like. All I need to know is how to, (i) take the Rmd file from the R Notebook creation process, and (ii) run the following code chunk:

# create "clean" HTML from Rmd file
library(knitr)
library(markdown)
knit("parCoord_notebook.Rmd") # produces a .md file
markdownToHTML("parCoord_notebook.md", "parCoord_notebook.html",         fragment.only=TRUE) # produces clean .html

The HTML file so produced couldn't be exactly like the R Notebook HTML file shown in the picture above, but comes complete with narrative, codes and images (plots), but without the heading of the post, namely, “R Notebook version of my parallel coordinates plots”, and without the button on the page that allows you to download the Rmd file. This Blogger-HTML version of my Notebook will be published as my next post. The only formatting I've done to this file before posting is to open it in Notepad++ and use its facility to remove blank lines.

The Rmd file is what makes the R Notebook fully reproducible. When you run it in the RStudio, the complete R Notebook is produced. RStudio provides services for you to share documents publicly or privately. You may as well use email or some cloud service to share them.

I've uploaded the full HTML file of the Notebook (parCoord_notebook.nb.html) to the Google Drive. You could download it from here.


Sunday, November 12, 2017

Zawgyi's beard, butterfly gamon, or black bat flower


Recently I've had the chance to see one of our nieces call for help on the Facebook to identify a flower via my wife's page. I at once recognized it through its shape to be what we knew as butterfly gamon which my late big sister grew a long time ago.



I googled for ဂမုန်းလိပ်ပြာ and found the following page on Wikipedia in Myanmar language:


Searching with the image of the flower on Google I found out its scientific name to be Tacca chantrieri. Looking up, I found Wikipedia's entry as:

Comparing the Myanmar version with the English version of the description of this flower I was unhappy because the Myanmar version seems to be relying too much on folklore and falls short on science as if the author(s) were entirely unaware of the English version. They could at least have given its scientific name in the Myanmar version, I thought.

This reminds me of the way modern day researchers criticized the math genius Ramanujan when he wrote about squaring the circle (Arndt and Haenel 2001, Pi Unleashed, p. 58).


What I would like to say is that including elements of Myanmar folklore in an Wikipedia article certainly makes it colorful and interesting. But they have to be pointed out as such. For example, instead of writing like
One who cares for the Zawgyi gamon is likely to win in lottery or Its leaves should not be cut off. If done, quarrels between husband and wife are likely to happen or A tea-cupful of liquid extract obtained by grinding its leaves taken for about ten days cure the coughing up of blood (consumption),
quotation marks could be placed around them. Or a phrase like “Many believe that ...” could be added to make it more explicit that we are dealing with folklore.

The Wikipedia's philosophy that an article like Zawgyi Beard Gamon which ranks as a Stub will have contributions to expand and improve it as it called for and hoped, didn't materialize for this particular case and maybe for many more. I guess that is because we Myanmars were so late in getting interested in, and involved with, Wikipedia or other sites and services on the Internet, except of course, the immensely popular Facebook.

If we Myanmars were not interested, wouldn't any non-Myanmars be? We don't know. But if they were interested, most of them may try for a Google translation, for example, to make sense out of an article like “Zawgyi Beard Gamon” in Myanmar language. This is what they would get now:

What you see is a translation where the original is not at all recognizable. It is distorted and looks funny. But in reality, it isn't a laughing matter at all. Yes, Google Translation has problems but it may not be entirely Google's fault because it is successful with other languages.

Google Translate first added Myanmar language in December 2014. According to the official Google Translate Blog:

  • Myanmar (Burmese, မြန်မာစာ) is the official language of Myanmar with 33 million native speakers. Myanmar language has been in the works for a long time as it's a challenging language for automatic translation, both from language structure and font encoding perspectives. While our system understands different Myanmar inputs, we encourage the use of open standards and therefore only output Myanmar translations in Unicode. ...
We’re just getting started with these new languages and have a long way to go. You can help us by suggesting your corrections using "Improve this translation" functionality on Translate and contributing to Translate Community.

Well, Google Translate is using 'neural machine translation engine - Google Neural Machine Translation (GNMT) - which translates "whole sentences at a time", rather than just piece by piece'. This sounded to me like they are doing something very advanced and very good.

While the technology of the translation engine is way beyond our heads, it is not hard to understand that it needs data to use in its process of grinding out translations . For that Google Translate seems to need at least a collection of the same text in a pair of languages (Myanmar and English versions, for example) of more than 150-200 million words, and another collection of more than a billion words each for Myanmar and English separately.

So it seems we could improve translations from Myanmar to other languages (not only with Google's GNMT, but possibly with other approaches) generally by making available a wider range of material to work on. That means making documents in Myanmar language in digital format widely available and in big volume - the bigger the better. That also means making sure they are in Unicode format. Why? Because, it seems so obvious.