简体   繁体   中英

How do I run r function as R script?

I have a function called function_test saved as testcode.r file. I have been running it like this (with all the required parameters within R environment):

function_test(p1, p2 , p3 , p4)

What do I need to do to Run it like this in linux terminal?

Rscript testcode.r \

–p1 param1 \

–p2 param2  \

–p3 param3 \

--p4 param4 

Try this:

Add this as the first line to your function file, before the function definition starts:

args=commandArgs(trailingOnly = TRUE)

Depending on the number of arguments required by your function:

function_test(param1=args[2],param2=args[3],param3=args[4],param4=args[5])

The args vector stores everything you pass from command line as a character, so you might have to do type conversion if your function is expecting objects as a numeric for example.

Then call your script from command line like this:

Rscript testcode.r --args arg1 arg2 arg3 arg4 

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM