R Characters

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)
[1] "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
[1] "3.14159265358979"
> class(x)     # print the class name of x
[1] "character"

Characters can be concatenated by the paste() function.

> name <- "Clounce"
> description <- "the best!"
> paste(name, description)
[1] "Clounce the best!"

Note that the paste() functions adds a space between the two variables. Cool eh!

Three common functions associated with strings are sprintf(), substr(), and 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) 
[1] "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)
[1] "the"
>

Replacing part of string can be done using the sub() function.

> sentence
[1] "Clounce the best!"
> sub("best", "great", sentence)
[1] "Clounce the great!"
>