liveBook · Manning

User-defined function

As explained in Statistics Slam Dunk

A user-defined function is a named, programmer-authored block of code that accepts inputs and returns a result or performs an operation.

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

How Statistics Slam Dunk covers it

How deep it goes
Defines names, arguments, bodies, return values, calls, and missing-argument behavior through short worked examples.
Examples
Uses correlation conversions, Gini estimation, Lorenz-curve values, returned results, and a missing-argument error.
What you can do after
Build it from scratch in R by defining functions, passing arguments, returning values, and reusing calculations.
How it connects
Connects user-defined functions to functional programming, built-in functions, for loops, Gini coefficients, and Lorenz curves.

Also explained in

Compare how 2 books explain user-defined function →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Statistics Slam Dunk. The section links point to the parts of the book it draws on.