13

I am layman to unix and sofar I using R in windows. For example I type following in my R session (in R gui).

# this is a my funny example script 
X <- 1:10
Y <- 21:30
plot(X, Y)
myfun <- function (x){
              x1 <- x^0.2
              return (x1)
             }
myfun(X)

How can I achieve this in unix shell, in two situations -

(1) directly in command line via an interpeter (2) creating a script and running script.

Please provide step considering I am layman to unix.

SHRram
  • 4,127
  • 7
  • 35
  • 53
  • 1
    Maybe you should use R for linux? – Burton Samograd May 15 '12 at 14:32
  • Sorry for the simple question, what is the difference between linux and unix R ? I believe we can run R in unix – SHRram May 15 '12 at 14:35
  • 1
    What have you tried? R should install nicely on unix or linux, and you can access it through the command line with `R`. You can also look at some of the excellent guis available (I would suggest [RStudio](http://www.rstudio.org) as an excellent starting point). Finally, running a script can be done easily. Often you use `R CMD BATCH script.R` but there are many alternatives and options that are well documented. – Justin May 15 '12 at 14:45
  • 2
    I suggest you go through the [`R` documentation](http://cran.r-project.org/manuals.html). There you have good instructions for [installation](http://cran.r-project.org/doc/manuals/R-admin.html#Installing-R-under-Unix_002dalikes) and e.g. [scripting](http://cran.r-project.org/doc/manuals/R-intro.html#Scripting-with-R). – Maehler May 15 '12 at 14:46

4 Answers4

25

Assuming you save your script in a simple text file with the name so.R, you can run it under Linux/Unix by typing R at the prompt. Once in R enter

  source('so.R')

to execute the script inside the R environment (this assumes the so.R file is in the same directory as you are when you issue this command).

To run the script from the Linux/Unix command line use the following command:

  R CMD BATCH so.R

Note that I got the plot to show when I ran the script inside of R, but from the Linux command line it doesn't show. I suspect it gets quickly displayed and then goes away, so there will be a R command that you have to look up to make it pause after it displays the plot.

Levon
  • 138,105
  • 33
  • 200
  • 191
  • 4
    You may want to consider actual scripting fronted `Rscript` (comes with R) or our older `r` (from our package littler). The use of `R CMD BATCH` is deprecated in favor of Rscript. If you have it, r is nice too. – Dirk Eddelbuettel Sep 30 '13 at 18:42
1

I'm guessing from the way you worded your question that you maybe SSH'ed into a linux machine? Or that you installed Ubuntu, for example, on your usual laptop/PC.

Assuming it's the second case: open a terminal and type sudo apt-get install r-base. Then type R. Then type

X <- 1:10
Y <- 21:30
plot(X, Y)
myfun <- function (x){
              x1 <- x^0.2
              return (x1)
             }
myfun(X)

Since your question is about unix versus linux rather than R, you might also try http://unix.stackexchange.com. There is a lot to be said about the differences between linux and unix, but all you probably need to know is: download Ubuntu, burn it onto a disc, then restart your computer with the disc in your CD drive.

Hope this helps.

isomorphismes
  • 8,233
  • 9
  • 59
  • 70
1

If your program is going to work on a single dataset, then simple-r might be the solution:

http://code.google.com/p/simple-r/

It is especially designed for simple statistical analysis as a part of Linux command line. For example, if one wants to plot some data, 'r -p data.txt' will do the job; for getting correlation coefficient: 'r cor data.txt' will suffice.

Tom
  • 41
  • 1
1

The examples below show two ways to run R code in a shell script. Both examples will also define functions without executing them, if the scripts are loaded to an interactive R session via the source() function.

The first example allows you to give arguments as you would to any other shell script, but will not pass additional R-options to R (because Rscript gives "--args" to R as one of the arguments).

The second example allows you to give additional R-options, but generates (harmless) warning messages unless you give "--args" as one of the script arguments. This version is best avoided unless you have special requirements.

prototype-Rscript.r

#!/usr/bin/env Rscript
# Prototype R script for use at command line in Linux, Mac OS X, UNIX

# References:
#   Manual "A Introduction to R", available via help.start() from the R Console
#   Appendix "B.1 Invoking R from the command line" in "A Inroduction to R",

showArguments <- function(argv)  {
    print(argv)
    0
}

if ( ! interactive() )  {
    # set some error return codes
    SCRIPT_ERROR <- 10                      # see documentation for quit()
    SCRIPT_ARG_ERROR <- SCRIPT_ERROR + 1

    # Define ARGV as script path concatenated to script arguments
    ARGV <- commandArgs(FALSE)          # start with all the arguments given to R
    scriptPath <- sub("^--file=", "", grep("^--file=", ARGV, value=TRUE)) [[1]]
    ARGV <- c(scriptPath, commandArgs(TRUE))

    if (length(ARGV) < 2)   {
        cat(file=stderr(), sep="",
            "Usage: ", ARGV[[1]], " [ options ] item ...\n",
            "       Do something with item\n",
            "       See script for details\n")
        quit(save="no", status=SCRIPT_ARG_ERROR)
    }
    quit(save="no", status=showArguments(ARGV))
}

prototype-shellscript.r

#!/usr/bin/env R --slave --vanilla --quiet -f
# Prototype R script for use at command line in Linux, Mac OS X, UNIX

# References:
#   Manual "A Introduction to R", available via help.start() from the R Console
#   Appendix "B.1 Invoking R from the command line" in "A Inroduction to R",

showArguments <- function(argv)  {
    print(argv)
    0
}

if ( ! interactive() )  {
    # set some error return codes
    SCRIPT_ERROR <- 10                      # see documentation for quit()
    SCRIPT_ARG_ERROR <- SCRIPT_ERROR + 1

    # Define ARGV as the arguments given to this script (after argument “-f”)
    ARGV <- commandArgs(FALSE)          # start with all the arguments given to R
    ARGV <- ARGV[(grep("-f", ARGV) [[1]] + 1):length(ARGV)]
    if ( any(grepl("--args", ARGV) ))   {   # remove arguments intended only for R
        ARGV <- c(ARGV[[1]], commandArgs(TRUE))
    }

    if (length(ARGV) < 2)   {
        cat(file=stderr(), sep="",
            "Usage: ", ARGV[[1]], " [ R_options ] --args [ options ] item ...\n",
            "       Do something with item\n",
            "       See script for details\n")
        quit(save="no", status=SCRIPT_ARG_ERROR)
    }
    quit(save="no", status=showArguments(ARGV))
}