[R] Write and Load functions from an external file
Uwe Ligges
ligges at statistik.tu-dortmund.de
Fri Feb 13 16:41:03 CET 2009
Moumita Das wrote:
> Hi All,
>
> Would be grateful,if anyone can answer my queries.
>
>
> I need to share code. For example, if I am working in C/C++, I would put
> some function declarations in .h files that you would include. In PHP, I
> would create files with the common functions in them and then "include()"
> them. So far, I haven't been able to figure out what the standard practice
> is in R.
>
>
>
> The two options are:
>
>
>
> 1. Write everything in one file. No sharing of functions.
>
> 2. Write libraries - but you *have to package it* first to use it.
What you probably want is 2: Write a *package*. Packaging it does not
take ages once you have tried it ...
Uwe Ligges
>
>
> Neither is a good option. how you I share functions across two scripts?
>
>
>
> there is "source()"
>
> But are there any other way?
>
> For example, in python, what I do is create common functions in a separate
>
> file (say, called A), use those functions from file B by including it like I
>
>
> would any other library. Then when I'm ready to 'release' it, I can package
>
> the library and the script...
>
>
>
> I did find something:-----
>
> http://www.ma.hw.ac.uk/~stan/R/Rnotes.pdf<http://www.ma.hw.ac.uk/%7Estan/R/Rnotes.pdf>says
> :--
>
>
>
> To create and edit functions, use the (built-in) R function edit. (As usual,
> type ?edit at
>
> the command prompt for details|see Section 10.)
>
> Alternatively the function source|also available via the File menu|can be
> used to input
>
> lengthy function denitions from an externally edited le. (The function dump
> will write an
>
> existing function denition to a file.)
>
> But then source() also ,not only loads but parses the file too.
>
>
> https://stat.ethz.ch/pipermail/r-help/2007-October/142938.html
>
> You can save one or more functions and datasets to a file (see ?save) then
> on starting another session attach that file (see ?attach).
>
> The process is like:---
>
>
>
> foo <- function(x) mean(as.numeric(x), trim = 0.3)
>
> save(foo, file = "myproject/rfunctions/saved.rda")
>
>
>
> then, when starting a new session, use
>
>
>
> attach("myproject/rfunctions/saved.rda")
>
>
>
> The .rda extension on the filename is commonly used for saved R data
>
> sets but you can also have function definitions in a saved file.
>
> Are these the only ways,and the best ways,to do what I want?
>
>
> *--
> Thanks
> Moumita*
>
More information about the R-help
mailing list