【问题标题】:Rscript optparse ggplotRscript optparse ggplot
【发布时间】:2017-01-20 05:43:27
【问题描述】:

我已经设置了一个 Rscript 来从命令行解析选项。它可以很好地解析文件名,但是当我尝试通过命令解析指定要在 x 或 y 轴上绘制的内容时,它无法识别我要绘制的字段。这是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()

这是数据文件:

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

这里是命令行:

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

【问题讨论】:

    标签: r ggplot2 optparse rscript


    【解决方案1】:

    这不是optparse 的问题,而是ggplot2 的延迟评估。

    这是一种解决方法:使用从 optparse 获得的“引用字符串”来 将您的数据子集到一个新的(临时)data.frame 中,然后从中绘制。 IE。使用这三行:

    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))
    

    这样我得到了想要的情节,如下所示。哦,我认为 docoptoptparse 好很多。

    【讨论】:

    • 很高兴听到。 StackOverflow 的工作方式是,您应该通过单击标记(只有您作为原始海报看到)来“接受”一个有效的答案(或几个最佳答案)。此外,您还可以通过单击向上箭头来“投票”。该系统是基于绩效的,因此更好的答案可以获得奖励。
    猜你喜欢
    • 2011-10-15
    • 2019-05-12
    • 2021-07-09
    • 2011-11-22
    • 2012-07-30
    • 1970-01-01
    • 2011-08-29
    • 2013-03-07
    • 1970-01-01
    相关资源
    最近更新 更多