library(stringr)
<- "Hello, R!"
hello <- str_length(hello)
length cat(hello, "- has", length, "characters")
Hello, R! - has 9 characters
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, R!"
hello <- str_length(hello)
length cat(hello, "- has", length, "characters")
Hello, R! - has 9 characters
This code has three functions:
library
: This function loads the package passed as the argument, e.g. library(stringr)
loads the stringr
packagestr_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 stringstr_sub
: Extract substrings