I am runnning a R script, but facing an error :
Rscript example.R "a,b,c"
I am running above code where a,b,c are elements of character vector passed as argument. The above code works fine if i pass numeric values (eg 1,5,6)
Code is :
library("optparse")
library("tldutils") # eval_string
# install.packages("tldutils", repos="http://R-Forge.R-project.org")
option_list <- list(
make_option(c("-c", "--count"), type="character", default="5",
help='Vector of numbers separated by commas and surrounded by ""',
metavar="number")
)
args <- parse_args(OptionParser(option_list = option_list))
print(args$c)
eval_string(sprintf("foo = c(%s)", args$c))
print(foo)
Error is :
Error in eval(expr, envir, enclos) : object 'a' not found
Calls: eval_string -> eval.parent -> eval -> eval
Execution halted
Please help me, where i need to edit in code?
Not sure if I get exactly what you are after but with this I hope you will be able to figure out the details on your own and solve your problem.
The easiest way to pass a character vector to R as an argument would be to use the commandArgs
function (of the base package, no need to install anything fancy).
# Start R from the shell
$ R --args a,b,c
# Within R
> commandArgs()
[1] "/usr/lib64/R/bin/exec/R" "--args"
[3] "a,b,c"
If you only want to get the arguments specified after --args
use trailingOnly=TRUE
. Add strsplit
to turn "a,b,c"
into a three element vector. Alternatively, change the commas to spaces and you don't need strsplit
.
$ R --args a,b,c
...
> strsplit(commandArgs(TRUE), ",")[[1]]
[1] "a" "b" "c"
$ R --args a b c
...
> commandArgs(T)
[1] "a" "b" "c"
The "a,b,c" you are passing to the script get interpreted as variable names, not as strings.
Edit: anyway, I don't see why you want to pass data as an argument instead of a) reading it from standard input or better b) reading it from a file using for example read.table
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.