Run R script from command line

前端 未结 7 1764
甜味超标
甜味超标 2020-11-22 09:20

I have a file, called a.r, it has a chmod of 755,

sayHello <- function(){
   print(\'hello\')
}

sayHello()

Ho

7条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-22 09:29

    If you want the output to print to the terminal it is best to use Rscript

    Rscript a.R
    

    Note that when using R CMD BATCH a.R that instead of redirecting output to standard out and displaying on the terminal a new file called a.Rout will be created.

    R CMD BATCH a.R
    # Check the output
    cat a.Rout
    

    One other thing to note about using Rscript is that it doesn't load the methods package by default which can cause confusion. So if you're relying on anything that methods provides you'll want to load it explicitly in your script.

    If you really want to use the ./a.R way of calling the script you could add an appropriate #! to the top of the script

    #!/usr/bin/env Rscript
    sayHello <- function(){
       print('hello')
    }
    
    sayHello()
    

    I will also note that if you're running on a *unix system there is the useful littler package which provides easy command line piping to R. It may be necessary to use littler to run shiny apps via a script? Further details can be found in this question.

提交回复
热议问题