A few R patterns

  1. Plotting a matrix of small charts on one page:

    #setup a (close to) square matrix for plotting
    matrix_par <- function(numplots, ...) {
       par(mfrow = c(ceiling(numplots / floor(sqrt(numplots))), floor(sqrt(numplots)) ),...);
    }
    
  2. Barplots with confidence intervals

    library(gplots);
    #plot a barplot with confidence intervals
    barplot_ci <- function (y, y_ci, ...) {
        barplot2(y, ci.l=y-y_ci, ci.u=y+y_ci, plot.ci=TRUE, ...);
    }
    
  3. Filtering certain columns in a data frame:

    restrict = c("val1", "val2", "val3");
    x = read.table(...);
    if (is.vector(restrict)) 
        x = x[ x$V1 %in% restrict, ];
    
  4. Cummulative series with sapply:

    sum_x = sapply(seq(x), function(i) { sum(x[1:i]); });
    
  5. Processing multiple files in a directory and generating output files

    #execute for all input files
    input_files = list.files(".","\.ssv");
    for(input_file in input_files) {
       #convert the filename according to this regexp
       output_file = sub("\.ssv","\.new_extension",input_file);
    }
    

Leave a Reply