0

I have a file on my computer that I want to run from the command line. This file would have some stuff happening within it + a function.

For example I have a global variable, start_value=10 and then I call a function further down in the Rscript. I want to run this script while passing in parameters

I tried to find out online how to do this, but I have had no luck.
I receive this error:

  Error in help_function(x, y) : object 'x' not found

When running like this:

    Rscript helpme.R 100 10

-

  ##?? saw this someplaces when searching, but couldn't get it to work
 args = commandArgs(trailingOnly=TRUE)

 starting_value=10

 help_function = function(x,y){


     division =x/y
     answer=starting_value + division
 return(answer)
}

 help_function(x,y)
runningbirds
  • 6,235
  • 13
  • 55
  • 94
  • 1
    You need to pick the arguments out of `args`, and process them if necessary, [as for example here](http://stackoverflow.com/questions/14167178/passing-command-line-arguments-to-r-cmd-batch/14167417#14167417). – Josh O'Brien Feb 20 '16 at 21:24
  • rather obvious that R can't find `x` if you never define it in your script... – Joris Meys Feb 20 '16 at 21:38

1 Answers1

0

commandArgs function returns a character vector with the arguments passed to the command line (trailingOnly = TRUE removes the "RScript helpme.R" part).

In your case :

args <- commandArgs(trailingOnly = TRUE)

# parse your command line arguments
x <- as.numeric(args[1]) # args[1] contains "100"
y <- as.numeric(args[2]) # args[2] contains "10"

# ...continue with your script here
digEmAll
  • 56,430
  • 9
  • 115
  • 140