0

I have setup an Rscript to parse options from the command line. It parses the file name fine, but when I try and specify what to plot on the x or y axis by command parsing, it doesnt recognize the field I am trying to plot. Here is the Rscript

#!/usr/bin/Rscript --vanilla
library(ggplot2)
library("optparse")

option_list = list(
  make_option(c("-f", "--file"), type="character", default=NULL,
              help="dataset file name", metavar="character"),
  make_option(c("-o", "--out"), type="character", default="out.txt",
              help="output file name [default= %default]", metavar="character"),
  make_option(c("-x", "--x_axis"), type="character", default="name",
              help="x axis value [default= %default]", metavar="character"),
  make_option(c("-y", "--y_axis"), type="character", default="score",
              help="y axis value [default= %default]", metavar="character")
);

opt_parser = OptionParser(option_list=option_list);
opt = parse_args(opt_parser);

data <- read.table(opt$file, header=TRUE)
p <- ggplot( data, aes( x=factor( opt$x_axis), opt$y_axis))

p + geom_boxplot()

Here is the data file:

character name score
A  54      3.589543
B  54      3.741945
C  60      3.585833
D  60      3.655622

Here is the command line:

./boxplot.R -f "file.txt" -o "test.png" -x "name" -y "score"

1 Answers1

0

This is not your problem with optparse, rather it is delayed evaluation biting you from ggplot2.

Here is a workaround: use the 'quoted strings' you get from optparse to subset your data into a new (temporary) data.frame and then plot from that. I.e. use these three line:

data <- read.table(opt$file, header=TRUE)
newdata <- data.frame(x=as.factor(dataset[, opt$x_axis]),
                      y=dataset[,opt$y_axis])
p <- ggplot( newdata, aes(x=x, y=y))

With that I get the plot as desired and shown below. Oh, and for what it is worth I think docopt is a lot nice than optparse.

enter image description here

Dirk Eddelbuettel
  • 360,940
  • 56
  • 644
  • 725
  • Glad to hear. The way StackOverflow works is that you are expected to 'accept' a working answer (or best among several) by clicking on the tickmark (which only you as original poster see). Additionally, you may also 'upvote' by clicking on the up arrow. The system is merit based so that better answers get rewards. – Dirk Eddelbuettel Sep 14 '16 at 14:02