my_function <- function() {
statements/instructions to do something
return(result of instructions)
}
name
is assigned an object
; orobject
is set to name
<-
age <- 22
age <- as.numeric(c("22", "25", "19"))
Functions are special objects which contain statements for carrying out operations
c()
or Hmisc::Cs()
: to combine elements into a vectormean()
: to compute the mean of a numeric vectorsource()
: for reading/executing R
codedplyr::mutate()
: for creating variables in data framesrio::import()
or readr::read_csv()
: for reading data filesreadRDS()
: for reading compressed data files5 terms concepts to know:
name
(created by assignment operator <-
)definition
(code statements or instructions for its usage)arguments
(optional variables that specify the function’s operation)function call
(e.g., execution of a function)returned object
(value returned from the executed function)my_function <- function() {
statements/instructions to do something
return(result of instructions)
}
get_years_since_birth <- function(dob) {
if (!hasArg(dob)) {
message("Error: dob missing/no argument provided")
}
else {
# make string a data
dob = lubridate::as_date(dob)
# obtain the difference in time in days
diff = difftime(time1 = Sys.Date(), time2 = dob, units = "days")
# create age based on days in year
age = as.numeric(diff / 365.25)
# return the age in years, truncated
return(trunc(age))
}
}
library(dplyr)
mutate()
(from {dplyr})eeptools::age_calc()
: for calculating age based on a date::
calls ensures choice (duplicate function names in different libraries)