Running a script

Problem

You want to run R code from a text file.

Solution

Use the source() function.

  1. # First, go to the proper directory
  2. setwd('/home/username/desktop/rcode')
  3. source('analyze.r')

Note that if you want your script to produce text output, you must use the print() or cat() function.

  1. x <- 1:10
  2. # In a script, this will do nothing
  3. x
  4. # Use the print function:
  5. print(x)
  6. #> [1] 1 2 3 4 5 6 7 8 9 10
  7. # Simpler output: no row/column numbers, no text wrapping
  8. cat(x)
  9. #> 1 2 3 4 5 6 7 8 9 10

Another alternative is to run source() with the print.eval=TRUE option.