0

我想写出一个.R文件或创建一个R scriptfrom R console,就像我们创建.txt文件一样。但是通常当我们写出.txt文件时,它们包含一些output而不是commands它。所以我想用 R 命令R scriptconsole写它。save

我不确定R是否有这样的write.R东西。我尝试使用sink()命令,但又一次outputs the output and not commands

 sink("Rscriptfrom_Console.R")
 sapply(iris,class)
 sink()

创建一个R script file (.R) from R console using R commands.

非常感谢任何帮助。谢谢!

4

2 回答 2

1

回答我自己的问题。如果您有更好的答案,请发布。使用 herefile()writeLines()function 并source()检查写入的.R文件是否正常工作。

  fc <- file("out.R")

  writeLines(c("print(head(iris))",
  "print(summary(iris))"),
  fc)

  close(fc)

  source("out.R")
  #   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
  # 1          5.1         3.5          1.4         0.2  setosa
  # 2          4.9         3.0          1.4         0.2  setosa
  # 3          4.7         3.2          1.3         0.2  setosa
  # 4          4.6         3.1          1.5         0.2  setosa
  # 5          5.0         3.6          1.4         0.2  setosa
  # 6          5.4         3.9          1.7         0.4  setosa

  #   Sepal.Length    Sepal.Width     Petal.Length    Petal.Width   
  #  Min.   :4.300   Min.   :2.000   Min.   :1.000   Min.   :0.100  
  #  1st Qu.:5.100   1st Qu.:2.800   1st Qu.:1.600   1st Qu.:0.300  
  #  Median :5.800   Median :3.000   Median :4.350   Median :1.300  
  #  Mean   :5.843   Mean   :3.057   Mean   :3.758   Mean   :1.199  
  #  3rd Qu.:6.400   3rd Qu.:3.300   3rd Qu.:5.100   3rd Qu.:1.800  
  #  Max.   :7.900   Max.   :4.400   Max.   :6.900   Max.   :2.500  

  #        Species  
  #  setosa    :50  
  #  versicolor:50  
  #  virginica :50  
于 2016-10-13T11:57:13.663 回答
0

您似乎误解了sink它的作用:它捕获输出并将其写入文件。它不会捕获未计算的 R 表达式,这是您想要做的。

要捕获未计算的 R 表达式,您需要将其包装在 内quote,或使用类似的机制。要使用您的示例:

quoted_expr = quote(sapply(iris, class))

现在quoted_expr包含 R 表达式。接下来,您需要将其转换为 R 代码的字符串表示形式:

code_representation = deparse(quoted_expr, backtick = TRUE)

此处不是绝对必要的backtick = TRUE,但始终使用它是一种很好的做法,因为在某些情况下它是必要的。

最后,我们可以将此代码表示形式写入文件:

writeLines(code_representation, 'code.r')

现在,上面的示例将固定的 R 表达式写入文件。我们不妨自始至终使用字符串。但是使用带引号的表达式而不是字符串使我们能够即时更改代码,而不必乱搞字符串(容易出错且效率低下)。例如,我们可以让用户决定在哪个 data.table 上工作:

dataset_name = 'mtcars' # Modify to your heart’s content
quoted_expr = substitute(sapply(dataset, class),
                         list(dataset = as.name(dataset_name)))

# `quoted_expr` is now:
sapply(mtcars, class)

… ETC。

于 2016-10-13T12:07:37.603 回答