Functions

A core building block of all programming languages is a function. A function is a reusable block of code that can be used over and over again in your program. A function takes inputs (called arguments), it then does something to those inputs to produce some outputs, which are returned to you.

You’ve already used many functions. Let’s look at, for example, this snippet of code

library(stringr)
hello <- "Hello, R!"
length <- str_length(hello)
cat(hello, "- has", length, "characters") 
Hello, R! - has 9 characters

This code has three functions:

All of the functions in stringr start with str_ and take a string (or vector/list of strings) as the first argument. Some other key functions are:

Exercise

Use ? to learn about the above stringr functions and have a play printing different strings to the console.

For example, we can look at the function str_c with

?str_c

Using the below example dataframe, we compared the different behaviour of cat vs str_c

df <- data.frame(
  name = c("Jean", "Thomas", "Daniel"),
  age = c(25, 30, 35),
  is_student = c(TRUE, FALSE, FALSE)
)
cat(df$name, "-", df$is_student)
Jean Thomas Daniel - TRUE FALSE FALSE
str_c(df$name, "-", df$is_student)
[1] "Jean-TRUE"    "Thomas-FALSE" "Daniel-FALSE"