2015年8月3日 星期一

8.3 Writing R that can be run in UNIX command lines

#! /usr/bin/env Rscript
# Useful website: http://stackoverflow.com/questions/2151212/how-can-i-read-command-line-parameters-from-an-r-script
options(echo=FALSE) # if you don't want to see commands in output file
args <- commandArgs(trailingOnly = TRUE)
# trailingOnly=TRUE means that only your arguments are returned, check:
# print(commandsArgs(trailingOnly=FALSE))

cat("Hello", args, "\n")

Return in UNIX:
>YukaideMacBook-Air:Desktop yukaizou$ ./script.R Kai

>Hello Kai 

Alternatively,
>YukaideMacBook-Air:Desktop yukaizou$ Rscript script.R Kai
>Hello Kai 

Another useful website here: http://www.cureffi.org/2014/01/15/running-r-batch-mode-linux/
It also shows how to use the optparse package to make options. That guy is a genius. I might follow the blog for some other materials.

# 8.6 update: learning how to add options
library(getopt)
library(optparse)

options(echo=FALSE) # if you don't want to see commands in output file
args <- commandArgs(trailingOnly = TRUE)
# trailingOnly=TRUE means that only your arguments are returned, check:
# print(commandsArgs(trailingOnly=FALSE))

option_list <- list(make_option(c("-a", "--avar"), action = "store", default = NA, type = "character",
                                help = "just a variable name"),
                    make_option(c("-v", "--verbose"), action = "store_true", default = TRUE,
                                help = "Should the program print the extra stuff out? [default %default]"),
                    make_option(c("-q", "--quiet"), action = "store_false", dest = "verbose",
                                help = "Make the program not verbose." )
                    )
opt <- parse_args(OptionParser(option_list = option_list))

if (opt$v) {
        cat("Haha, you might think this is an verbose. Quiet me by adding a little -q!", "\n")
}

if (!is.na(opt$avar) ) {
        cat("You have just typed in:", "\n")
        cat(opt$avar, "\n")
} else {
        cat("Please specify variable a", "\n")
}

沒有留言:

張貼留言