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)
Error in library(stringr): there is no package called 'stringr'
hello <-"Hello, R!"length <-str_length(hello)
Error in str_length(hello): could not find function "str_length"
cat(hello, "- has", length, "characters")
Hello, R! - has
Error in cat(hello, "- has", length, "characters"): argument 3 (type 'builtin') cannot be handled by 'cat'
This code has three functions:
library : This function loads the package passed as the argument, e.g. library(stringr) loads the stringr package
str_length : This function calculates the number of characters in the string passed in as the argument, returning the number of characters. When input the value of hello (namely Hello R) it returns the number 7.
cat : This prints its arguments to the screen, returning nothing.
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:
str_c : Modern replacement for cat
str_length : Count the number of characters in a string
str_sub : Extract substrings
NoteExercise
Use ? to learn about the above stringr functions and have a play printing different strings to the console.
CautionAnswer
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