7/15/2011

A summary of recent use of Latex and Sweave

Latex:
  1. \usepackage{wasysym} This package allows you to use wasy2 font family. To use this, you need to install all the related wasy packages from MiTeX. I recently used \Box to draw a small square box for my survey questionnaire;
  2. \usepackage{hyperref} and \usepackage{url} provide ways to handle URL and add hyperlink in the documents to link your reference, figures, tables, footnotes, etc;
  3. \newcommand{\Qitem}[1]{\hskip 0.4cm \$\Box\$ #1} % define item with a square checkbox  The \newcommand{\Name}[#para]{Statement #1,#2,....} provides a way to define function or macro;
R:
  1. When using ggplot with sweave, it is a good idea to resize the plot before output. These lines make it easy"
  2. library(ggplot2)
    
    maxFontSize = 10 
    FigWidth = 7.5 # cm 
    FigHeight = 5.5 # cm 
    inch = 2.54 # cm 
    # tweek the screen to get the right plot size in cm 
    windows(width=FigWidth/inch, height=FigHeight/inch, 
      pointsize=maxFontSize) 
    #..... (Some other stuff)
    p = ggplot(data =age, aes(x = factor(1), y = Freq, fill = ageGrp))
    p = p + geom_bar(width = 1) + opts(plot.background = theme_blank(),
      plot.margin = unit(c(1, 0, 0, 0.5), "lines")) 
    p = p + coord_polar(theta="y") 
    p = p + xlab('') +
     ylab('') +
     labs(fill='Age Group')  
    print.ggplot(p)
    ggsave("pie_chart_ageGrp.pdf",scale=1.5) 
    dev.off()
    <\pre>
    
  3. Multiple plots in ggplot
  4. You can easily plot multiple plots using ggplot like you did with par(mfrow=c(m, n)). Two commands: pushViewport and viewport  make this possible. Be remind to include vp statement in print.ggplot command.
    # First plot the stack bar chart
    p = ggplot(data = df, aes(x= factor(1), y = Summary, fill = factor(response)))
    p = p + geom_bar(width =1) + opts(plot.background = theme_blank()) 
    p = p+facet_grid(facets=. ~ gender)
    p = p + xlab('') + ylab('') + labs(fill='Response') + opts(axis.text.x = theme_blank())
    
    pushViewport(viewport(layout = grid.layout(2, 1)))
    vp1 <- viewport(width = 1, height = 0.5, just = c("bottom"))
    pdf("pie_chart.pdf")
    print.ggplot(p ,vp = vp1)
    # Second plot the pie chart
    p = p  + coord_polar(theta="y") 
    vp2 <- viewport(width = 1, height = 0.5, just = c("top"))
    print.ggplot(p,vp = vp2)
    <\pre>
    
  5. SQL in R
  6. Package "sqldf" comes in handy. After applying the package, you can use sql for more advanced data manipulation. For example,
    sumFreq = sqldf("
       select SUM(Freq) as 'SumFreq'
       From age")
    <\pre> 
    
    

    No comments: