R 教材:批次方法

  1. Hello world !
    First, create an R code file "hello_1.r" contains this

        
    # File name: hello_1.r
    a <- c("Hello", "world", "!")
    print(a)
    b <- paste(a, collapse = " ")
    print(b)
    

    Here, set an array variable "a" contains 3 elements, "Hello", "world", and "!", and print it. Then use the function "paste" to join all elements in array "a" by " " (space) and set to a variable "b" and print it.

  2. Batch From Script
    Use script mode to send "hello_1.r" for batch job,

         SHELL> R CMD BATCH --vanilla --slave hello_1.r output_file

    by default the output will be saved in "hello_1.r.Rout" if the "output_file" doesn't assigned. And the output file (hello_1.r.Rout) will like this,

         > a <- c("Hello", "world", "!")
    > print(a)
    [1] "Hello" "world" "!"
    > b <- paste(a, collapse = " ")
    > print(b)
    [1] "Hello world !"
    >


  3. Batch From Command
    Use command mode to send "hello_1.r" for batch job from STDIN and show the output on SDTOUT, and the follows are the same,

         SHELL> R --vanilla --slave < hello_1.r > output_file
         or
         SHELL> cat hello_1.r | R --vanilla --slave > output_file
         or
         SHELL> echo 'source("hello_1.r")' | R --vanilla --slave > output_file

    by default the output will be show on the screen, can use ">" to redirect the output into "output_file". And the output will show this,

         [1] "Hello" "world" "!"
    [1] "Hello world !"


  4. Windows
    Use "Rterm.exe" or "Rcmd.exe" to substitute "R" in batch mode.

  1. Hello world, MOLAS !
    First, create an R code file "hello_2.r" contains this

        
    # File name: hello_2.r
    a <- c("Hello", "world,", argv, "!")
    print(a)
    b <- paste(a, collapse = " ")
    print(b)
    

    Here, set an array variable "a" contains 4 elements, "Hello", "world,", argv, and "!", and print it. The variable "argv" will be passed from STDIN command. Then use the function "paste" to join all elements in array "a" by " " (space) and set to a variable "b" and print it.

  2. Pass Variable From STDIN
    Use command mode to send "hello_2.r" for batch job from STDIN and show the output on SDTOUT. And before "hello_2.r" also pass the variable "argv" as "MOLAS",

         SHELL> echo 'argv <- "MOLAS"; source("hello_2.r")' | R --vanilla --slave > output_file

    by default the output will be show on the screen, can use ">" to redirect the output into "output_file". And the output will show this,

         [1] "Hello" "world," "MOLAS" "!"
    [1] "Hello world, MOLAS !"

[BCC16-B]
陳韋辰 (04/08/19) ---
[Prev] [Next] [Up]