Introduction to Functions

As in most programming languages, the heart of R programming consists of writing functions. A function is a group of instructions that takes inputs, uses them to compute other values, and returns a result.

As a simple introduction, let’s define a function named oddcount(), whose purpose is to count the odd numbers in a vector of integers. Normally, we would compose the function code using a text editor and save it in a file, but in this quick-and-dirty example, we’ll enter it line by line in R’s interactive mode. We’ll then call the function on a couple of test cases.

# counts the number of odd integers in x > oddcount <- function(x) { + k <- 0 # assign 0 to k + for (n in x) { + if (n %% 2 == 1) k <- k+1 # %% is the modulo ...

Get The Art of R Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.