print_something <- function(some_string_provided_by_user) {
print(some_string_provided_by_user)
}
print_something(some_string_provided_by_user = "Good morning!")
[1] "Good morning!"
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)
}
print_strictly_two_options <- function(user_selected_string = c("hello", "hi")) {
if (user_selected_string %in% c("hello", "hi")) {
print(user_selected_string)
} else {print("This value is not allowed. Please choose `hello` or `hi`.")}
}
print_strictly_two_options("wow")
[1] "This value is not allowed. Please choose `hello` or `hi`."
print_in_case <- function(string_from_user, convert_q_to_upper = FALSE){
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)}
}
print_in_case("Basque")
[1] "Basque"
[1] "BasQue"
result: the output of the last line
do not assign it to variable
or use return(variable)
as last line
Writes a file in the working directory, but will not save anything to a variable.
normally a result is visible but can be made invisible
print
, readr::write_lines
unlike writeLines
returning NULL
)That printed “hello” but also saved it into the variable:
this is called argument forwarding
sample()
returns the whole sample by default.