An R Introduction to Statistics

Character

A character object is used to represent string values in R. We convert objects into character values with the as.character() function:

> x = as.character(3.14) 
> x              # print the character string 
[1] "3.14" 
> class(x)       # print the class name of x 
[1] "character"

Two character values can be concatenated with the paste function.

> fname = "Joe"; lname ="Smith" 
> paste(fname, lname) 
[1] "Joe Smith"

However, it is often more convenient to create a readable string with the sprintf function, which has a C language syntax.

> sprintf("%s has %d dollars", "Sam", 100) 
[1] "Sam has 100 dollars"

To extract a substring, we apply the substr function. Here is an example showing how to extract the substring between the third and twelfth positions in a string.

> substr("Mary has a little lamb.", start=3, stop=12) 
[1] "ry has a l"

And to replace the first occurrence of the word "little" by another word "big" in the string, we apply the sub function.

> sub("little", "big", "Mary has a little lamb.") 
[1] "Mary has a big lamb."

More functions for string manipulation can be found in the R documentation.

> help("sub")