A user-defined function is a programmer-authored R function that packages a calculation or operation for reuse. Like built-in and packaged functions, it has a name, arguments, a body, and a return value. section 13.7
Build a function from four connected parts:
- Name the function with an intuitive identifier. section 13.7
- Declare arguments that supply the function’s inputs. section 13.7
- Place statements inside curly brackets to define the function body. section 13.7
- Return the output expected from the calculation. section 13.7
Convert a correlation to explained variance
Define r_to_rsquared() with r as its input, square r, and return the result. Calling r_to_rsquared(.42) returns 0.1764. A reverse function, rsquared_to_r(), takes 0.1764 and returns 0.42. section 13.7
r_to_rsquared <- function(r) {
rsquared <- r^2
return(rsquared)
}
Use this compact R listing to see assignment, an argument, a function body, an intermediate value, and an explicit return value together. section 13.7
Estimate a Gini coefficient
A gini.est() function accepts three Lorenz-curve values and returns an estimated Gini coefficient. Calling it with only two arguments produces a missing-argument error; supplying three values returns estimates such as 0.522. section 13.7

