简体   繁体   中英

Rscript optparse ggplot

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"

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. Ie 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 .

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM