2025-08-14
avoid repeated copy-pasting and adjusting of code
you can keep a separate file with functions
Write your long script.
For your future self, extract the functions from it and save them in a separate bare R file (.R).
In the main document with the script, apply the function source on that file. This will run the file and hence load all functions into your Global Environment.
source(<"path/YourFileWithFunctions">.R)<function_name)> <- function( arguments ) {
function body (a piece of code using the arguments)
}
[1] "Good morning!"
[1] "hello"
[1] "bye"
[1] "This value is not allowed. Please choose `hello` or `hi`."
print_in_case <- function(string_from_user, convert_q_to_upper = TRUE){
if (require(stringr) == FALSE) {
library(stringr)
}
if (convert_q_to_upper == TRUE) {
string_from_user <- str_replace_all(string =
string_from_user, pattern = "q",
replacement = "Q")
print(string_from_user)
} else {print(string_from_user)}
}[1] "BasQue"
[1] "Basque"
result: the output of the last line
do not assign it to variable
or use return(variable) as last line
[1] "HELLO"
[1] "HELLO"
NULLWrites a file in the working directory, but will not save anything to a variable.
NULL
[1] "./myresultstring.txt"
[1] TRUE
normally a result is visible but can be made invisible
print , readr::write_lines unlike writeLines returning NULL)[1] "hello"
That printed “hello” but also saved it into the variable:
[1] "hello"
this is called argument forwarding
sample() returns the whole sample by default.
[1] 7 8 3
[1] 6 3 10 5 2 4 9 7 8 1
[1] 3
Error in eval(expr, envir, enclos): object 'all_summed' not found