In today’s blog we take a look at string in R. Strings in R are represented by character objects.
Let’s keep Clounce in a variable:
> name <- "Clounce"
Now let’s print it on screen:
> print(name)  "Clounce"
Numbers can be converted to characters using the
as.character function. Let’s look at an example:
> x <- as.character(pi) > x # print the value of x  "3.14159265358979" > class(x) # print the class name of x  "character"
Characters can be concatenated by the
> name <- "Clounce" > description <- "the best!" > paste(name, description)  "Clounce the best!"
Note that the
paste() functions adds a space between the two variables. Cool eh!
Three common functions associated with strings are
sub(). Let’s look at each function separately.
sprintf() is useful to display data. It has the same C equivalent syntax.
> sprintf("I am %s. I like %f", name, pi)  "I am Clounce. I like 3.141593"
To get part of a string, use
substr(). Note that it takes the start and stop position of the text you want to extract. The first character has position 1.
> sentence <- paste(name, description) > substr(sentence, start = 9, stop = 11)  "the" >
Replacing part of string can be done using the
> sentence  "Clounce the best!" > sub("best", "great", sentence)  "Clounce the great!" >