Basic operations with strings
Number of characters in a string
The simplest possible operation that we can do with character strings is to query how long they are. In R we do this with the nchar()
function (not length()
!):
one <- "R"
nchar(one)
one <- "Really."
nchar(one)
Concatanating characters into strings
Concatenation is the process of creating strings from individual characters or other strings. In R the paste()
function is the workhorse for this operation.
first <- "Mr."
second <- "Nimbus"
paste(first, second)
The function paste()
accepts as many arguments as you like:
first <- "Mr."
second <- "Nimbus"
paste(first, first, first, second)
Note the space (" "
) between the concatenated parts. This appears because the argument sep
has this as the default value:
first <- "Mr."
second <- "Nimbus"
paste(first, second, sep=" ")
This you can set to anything else, even entire words:
first <- "Mr."
second <- "Nimbus"
paste(first, second, sep=" (nope) ")
Or nothing at all:
first <- "Mr."
second <- "Nimbus"
paste(first, second, sep="")
This is exactly the behavior of variant of this function paste0()
, which allows you to save writing out this argument:
first <- "Mr."
second <- "Nimbus"
paste0(first, second)
Printing to the console
R’s console displays us feeback from the console. In case we want to force the printing of some information to the console, the nicest way of doing that is with the message()
function, that wraps the information in a nice and clean way:
message("This is a message.")
The message()
function expects a character string as input argument. This is where the paste()
function can be extremely handy.
Note that we cannot do much with such messages (for now) - but they can be super informative for learning, and with them we can always ask about the internal state of our program.