Passing multiple arguments via command line in R

前端 未结 5 1203
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-06 07:49

I am trying to pass multiple file path arguments via command line to an Rscript which can then be processed using an arguments parser. Ultimately I would want something like

5条回答
  •  清歌不尽
    2021-01-06 08:31

    The way you describe command line options is different from the way that most people would expect them to be used. Normally, a command line option would take a single parameter, and parameters without a preceding option are passed as arguments. If an argument would take multiple items (like a list of files), I would suggest parsing the string using strsplit().

    Here's an example using optparse:

    library (optparse)
    option_list <- list ( make_option (c("-f","--filelist"),default="blah.txt", 
                                       help="comma separated list of files (default %default)")
                         )
    
    parser <-OptionParser(option_list=option_list)
    arguments <- parse_args (parser, positional_arguments=TRUE)
    opt <- arguments$options
    args <- arguments$args
    
    myfilelist <- strsplit(opt$filelist, ",")
    
    print (myfilelist)
    print (args)
    

    Here are several example runs:

    $ Rscript blah.r -h
    Usage: blah.r [options]
    
    
    Options:
        -f FILELIST, --filelist=FILELIST
            comma separated list of files (default blah.txt)
    
        -h, --help
            Show this help message and exit
    
    
    $ Rscript blah.r -f hello.txt
    [[1]]
    [1] "hello.txt"
    
    character(0)
    $ Rscript blah.r -f hello.txt world.txt
    [[1]]
    [1] "hello.txt"
    
    [1] "world.txt"
    $ Rscript blah.r -f hello.txt,world.txt another_argument and_another
    [[1]]
    [1] "hello.txt" "world.txt"
    
    [1] "another_argument" "and_another"
    $ Rscript blah.r an_argument -f hello.txt,world.txt,blah another_argument and_another
    [[1]]
    [1] "hello.txt" "world.txt" "blah"     
    
    [1] "an_argument"      "another_argument" "and_another"     
    

    Note that for the strsplit, you can use a regular expression to determine the delimiter. I would suggest something like the following, which would let you use commas or colons to separate your list:

    myfilelist <- strsplit (opt$filelist,"[,:]")
    

提交回复
热议问题