3

I'm trying to run some demo R code for the optparse package that I got from R-bloggers. I am using ubuntu 14.04

The code is:

#!/usr/bin/env Rscript
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")
                  ); 

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

if (is.null(opt$file)){
    print_help(opt_parser)
    stop("At least one argument must be supplied (input file).n",    
    call.=FALSE)
}

## program...
df = read.table(opt$file, header=TRUE)
num_vars = which(sapply(df, class)=="numeric")
df_out = df[ ,num_vars]
write.table(df_out, file=opt$out, row.names=FALSE)

If the entire script is saved in a file called yasrs.R using the call:

Rscript --vanilla yasrs.R

should return the help messages.

I get an error:

Rscript --vanilla yasrs.R Error in library(optparse) : there is no package called ‘optparse’

I have installed the package (optparse) through RStudio when writing the code and also ensured that it is installed when calling from the terminal. Both terminal and RStudio are running the same R version.

Any suggestions would be appreciated.

haffamoto
  • 66
  • 1
  • 9
  • Thanks @Spacedman. From .libPaths() my personal Rlibrary was missing from the Rscript paths. Adding the path to that location worked as did removing the --vanilla flag. – haffamoto Feb 23 '16 at 12:36

1 Answers1

2

Where did RStudio install optparse? Get that from packageDescription("optparse").

Then check the output of .libPaths() in your Rscript environment and your RStudio environment. Maybe RStudio stuck it somewhere that RScript doesn't look.

Then check that even though they may be the same version of R, they might be two different installations. What does R.home() say in each?

One or more of these things will show you why it doesn't find it. Solution is probably to write and run a little RScript that installs it, then you should be fairly sure its going to go in a location that RScript will find it in future.

Spacedman
  • 92,590
  • 12
  • 140
  • 224