I am just starting to work with R, and this has probably been answered previously. In other languages like Javascript and Python, one can split their code in multiple files and then export functions from one and import them in another, within your project.
Example in Python is
To export from one file:
def CountWords(words):
if words is not None:
NumberOfWords = [Eachword.count(' ') 1 for Eachword in words]
return NumberOfWords
To import in another file:
from wordcounter import CountWords
# use the CountWords function here
What is the equivalent of this in R?
CodePudding user response:
Technically, you can:
foo <- function() {
message("Hello")
}
dput(foo, "foo.R")
foo2 <- source("foo.R")$value
foo2()
#> Hello
Created on 2022-03-28 by the reprex package (v2.0.1)
But I have never seen anyone do this and the somewhat janky syntax is a good indication that what I wrote here is not inteded to save an load functions. You can also use saveRDS(foo, "foo.rds")
to save the function and readRDS("foo.rds")
to read it. Note that in both cases the name of the function is not stored so you need to assign it with foo3 <- readRDS("foo.rds")
.
I think what you would usually do is to create a file called (for example) "custom_functions.R" to store all your functions for a project and then use source("custom_functions.R")
at the start of each script to load them.
custom_functions.R:
# function to do stuff
foo <- function() {
message("Hello")
}
your normal script:
source("custom_functions.R")
foo()
#> Hello
You do not need to assign names in this case.
R also makes it very straightforward to create your personal package, which is another good option (see, e.g., https://r-pkgs.org/).