Define all functions in one .R file, call them from another .R file. How, if possible?
You can call source("abc.R")
followed by source("xyz.R")
(assuming that both these files are in your current working directory.
If abc.R is:
fooABC <- function(x) {
k <- x+1
return(k)
}
and xyz.R is:
fooXYZ <- function(x) {
k <- fooABC(x)+1
return(k)
}
then this will work:
> source("abc.R")
> source("xyz.R")
> fooXYZ(3)
[1] 5
>
Even if there are cyclical dependencies, this will work.
E.g. If abc.R is this:
fooABC <- function(x) {
k <- barXYZ(x)+1
return(k)
}
barABC <- function(x){
k <- x+30
return(k)
}
and xyz.R is this:
fooXYZ <- function(x) {
k <- fooABC(x)+1
return(k)
}
barXYZ <- function(x){
k <- barABC(x)+20
return(k)
}
then,
> source("abc.R")
> source("xyz.R")
> fooXYZ(3)
[1] 55
>
call an R Script from an other script
To call an RScript from another script, you need to source
it at the beginning:
source("H.R")
# H is now available
G = function(x) {
return(-exp(-1i * x) * Conj(H(x+pi)) )
}
If you want to clean up your functions, you can also build a package containing all your functions.
A little bit more of work, but definitely worth the effort!
Can't call function. Is there a setting that controls this?
you probably need to source it with source("kelvin_to_celsius.r")
# > kelvin_to_celsius(150)
# Error in kelvin_to_celsius(150) :
# could not find function "kelvin_to_celsius"
# > source("kelvin_to_celsius.r")
# > kelvin_to_celsius(150)
# [1] -123.15
How Do I Write R Package Documentation When I Have More than One Function to Perform a Composite Task?
EDIT: i've changed the code so that the output is a vector instead of a list.
You can combine your functions into a single function. Here's an example:
sums <- function(x, methods = c("sum", "squaredsum", "cubedsum")){
output <- c()
if("sum" %in% methods){
output <- c(output, ss = ss(x))
}
if("squaredsum" %in% methods){
output <- c(output, sss = sss(x))
}
if("cubedsum" %in% methods){
output <- c(output, ssq = ssq(x))
}
return(output)
}
by default, all three of your functions are called and the results are returned in a list.
You can specify just one or more of the functions, in that case it will only return the outputs of the called functions.
In your documentation, you can now treat each of the possible methods as variable that can be set.'
EDIT
there's a mistake in your cube function. a cube is not taken by i***2
. It's i**3
. The correct function is:
ssq <- function(x){
`%dopar%` <- foreach::`%dopar%`
foreach::foreach(i = x*x*x, .combine = "+") %dopar% {i**3}
}
Finding if my function inside an rscript file is been called by either an rmarkdown or an rscript
In my case the following solves the issue
Getting the file path that also includes filename and extension:
file_type <- try(rstudioapi::getSourceEditorContext()$path, silent = T)
Getting the file extension.
file_type <- tools::file_ext(file_type)
Then iff file_type = 'R'
the functionalities are turned on and for any other cases they are off.
if(file_type == 'R'){
...
}
In this specific case I only care that the extension is a '.R' and don't want to risk using the functionalities with anything else.
For example if you are running the function in the console then file_type = ''
and the functionalities will be off.
How to import only functions from .R file without executing the whole file
First of all, let me say that this really isn't a good idea. R is a functional programming language so functions are just like regular objects. There's not a strong separation between calling a function and assigning a function. These are all pretty much the same thing
a <- function(a) a+1
a(6)
# [1] 7
assign("a", function(i) i+1)
a(6)
# [1] 7
`<-`(a, function(i) i+1)
a(6)
# [1] 7
There's no difference between defining a function and calling an assignment function. You never know what the code inside a function will do unless you run it; therefore it's not easy to tell which code creates "functions" and which does not. As @mdsumner pointed out, you would be better off manual separating the code you used to define functions and the code you use to run them.
That said, if you wanted to extract all the variable assignments where you use <-
from a code file, you could do
cmds <- parse("fakeload.R")
assign.funs <- sapply(cmds, function(x) {
if(x[[1]]=="<-") {
if(x[[3]][[1]]=="function") {
return(TRUE)
}
}
return(FALSE)
})
eval(cmds[assign.funs])
This will evaluate all the function assignments of the "standard" form.
Related Topics
How to Learn How to Write C Code to Speed Up Slow R Functions
Error: --With-Readline=Yes (Default) and Headers/Libs Are Not Available
Comparison Between Dplyr::Do/Purrr::Map, What Advantages
R Package Xtable, How to Create a Latextable with Multiple Rows and Columns from R
How to Preserve Transparency in Ggplot2
Stl Decomposition of Time Series with Missing Values for Anomaly Detection
Quick/Elegant Way to Construct Mean/Variance Summary Table
R Glmnet:"(List) Object Cannot Be Coerced to Type 'Double' "
Ggplot2 Error:Discrete Value Supplied to Continuous Scale
Writings Functions (Procedures) for Data.Table Objects
Piecewise Regression with R: Plotting the Segments
Any Way to Pause at Specific Frames/Time Points with Transition_Reveal in Gganimate
Code Organisation in R Package Development
Insert Portions of a Markdown Document Inside Another Markdown Document Using Knitr
Avoid That Space in Column Name Is Replaced with Period (".") When Using Read.Csv()