Search code examples
rxtable

Sorting output of xtable


I have a data set with which I create a table, but now I would like the output to be sorted alphabetically. order, sort or sort.list I don't get to work. Here is an example of what I have.

library(maptools)
data(wrld_simpl)
tab.test <- xtable(subset(wrld_simpl@data, select=c(NAME, REGION)))
head(tab.test)
% latex table generated in R 2.15.1 by xtable 1.7-0 package
% Sun Nov  4 19:58:19 2012
\begin{table}[ht]
\begin{center}
\begin{tabular}{rll}
  \hline
 & NAME & REGION \\ 
  \hline
ATG & Antigua and Barbuda &  19 \\ 
DZA & Algeria &   2 \\ 
AZE & Azerbaijan & 142 \\ 
ALB & Albania & 150 \\ 
ARM & Armenia & 142 \\ 
AGO & Angola &   2 \\ 
   \hline
\end{tabular}
\end{center}
\end{table}

I would like to be able to sort it by NAME, REGION or even the first column, which is ISO3 and seems to be the default left column. I appreciate your help, including hints to similar questions (I might have overlooked them during my search for a cure).


Solution

  • This has nothing to do with xtable as far as I can see

    Given that wrld_simpl is a SpatialPolygonsDataFrame I think it will be easier to work with a copy of the data slot that attempt to modify an S4 object.

    The plyr package has a nice function arrange which makes ordering easy. It is not clear whether you want them arranged by NAME and then REGION so I will give the example of ordering by NAME alone

    wrld_data <- wrld_simpl@data
    
    
    library(plyr)
    
    arranged_data <- arrange(wrld_data, NAME)
    # this was nice syntax for
    # wrld_data[order(wrld_data$NAME),]
    
    # subset colums
    subset_data <- subset(arranged_data, select = c(NAME, REGION))
    
    head(subset_data)
    
               NAME REGION
    1 Aaland Islands    150
    2    Afghanistan    142
    3        Albania    150
    4        Algeria      2
    5 American Samoa      9
    6        Andorra    150
    

    And just to show your issue was not xtable related

    .x <- xtable(subset_data)
    
    head(.x)
    % latex table generated in R 2.15.2 by xtable 1.7-0 package
    % Mon Nov 05 13:03:27 2012
    \begin{table}[ht]
    \begin{center}
    \begin{tabular}{rlr}
      \hline
     & NAME & REGION \\ 
      \hline
    1 & Aaland Islands & 150 \\ 
      2 & Afghanistan & 142 \\ 
      3 & Albania & 150 \\ 
      4 & Algeria &   2 \\ 
      5 & American Samoa &   9 \\ 
      6 & Andorra & 150 \\ 
       \hline
    \end{tabular}
    \end{center}
    \end{table}