1

I know that file.create() can generate an empty file, but my request is to generate an R script filled with specific text, such as

#' This is specific text 

#' So is this

foo <- function(x){
  bar(x)
}

How can I save this text in a way that it populates a file I generate via file.create() or through some other function?

Joe
  • 3,217
  • 3
  • 21
  • 37

1 Answers1

2

There is nothing special about R script files. They are simply text files and you can use writeLines to write them to a file:

script <- "
foo <- function(x){
  bar(x)
}
"
writeLines(script, "script.R")

Here is a simple case to test:

script <- "
print('hello world!')
"
writeLines(script, "script.R")
source("script.R")
#> [1] "hello world!"
JBGruber
  • 11,727
  • 1
  • 23
  • 45
  • Any workaround when doing this for longer 'scripts' that naturally have lots of quotation marks and curly braces, multiple separate function calls, etc? – coip Aug 24 '22 at 23:45
  • 1
    You need to escape some of the characters then. You could use `readLines` to read an existing script and look what gets escaped. Usually I start reading in a base script, replace the parts which need replacement and write it back out. The other day I wrote a simple function for that using `{{newspaper}}` as a placeholder which gets replaced: https://github.com/JBGruber/paperboy/blob/f9d125011fc51396db685445b49ad963f52424dc/R/utils.R#L17-L19 – JBGruber Aug 25 '22 at 11:36