运行R脚本

问题

你想从文本文件运行R代码

解决

使用source()函数。

  1. # 首先,选择合适的目录
  2. setwd('/home/username/desktop/rcode')
  3. source('analyze.r')

请注意,如果你想让你的脚本生成文本输出,你必须使用print()cat()函数。

  1. x <- 1:10
  2. # 在脚本中,这什么都不做
  3. x
  4. # 使用print()函数:
  5. print(x)
  6. #> [1] 1 2 3 4 5 6 7 8 9 10
  7. # 更简单的输出: 没有行/列,没有文本
  8. cat(x)
  9. #> 1 2 3 4 5 6 7 8 9 10

另一种代替方法是:运行source()并加上print.eval=TRUE选项。


原文链接:http://www.cookbook-r.com/Data_input_and_output/Running_a_script/