5

Given a function, how to save it to an R script (.R)?

Save works well with data, but apparently can not create .R data.

Copy pasting from the console to a new script file appears to introduce characters that cause errors.

Etienne Low-Décarie
  • 13,063
  • 17
  • 65
  • 87
  • 2
    Related: [Turning RData file into script files](http://stackoverflow.com/questions/3835714/r-turning-rdata-file-into-script-files) – Joshua Ulrich Jun 15 '12 at 18:10

2 Answers2

8

Take a look at the dump function. That writes files that are R code that can be read back in with source or used in some other way.

Brian Diggs
  • 57,757
  • 13
  • 166
  • 188
  • Is there a way to get the name space/environment specified with the function to also be dumped to the R file? If I want to edit a function from a package but still have this new function access the same name space as its original? – Etienne Low-Décarie Jun 16 '12 at 15:02
  • 1
    I don't believe there is. You would have to call `assignInNamespace` for that. – Brian Diggs Jun 17 '12 at 02:40
3

I have to ask: why are you writing your functions in the console in the first place? Any number of editors support a "source" call, so you can update the function as you edit. Copy/pasting from the console will carry prompt characters along , if nothing else, so it's a bad idea to begin with.

Carl Witthoft
  • 20,573
  • 9
  • 43
  • 73
  • Found myself doing this 'at the console stuff' while noodling around with some useful seqle (cgwTools pkg) functions and didn't want to lose the insights. – Chris Jan 20 '20 at 18:25