The Art of R Programming

(WallPaper) #1

As you can see, the optional argumentsepcan be used to put something
other than a space between the pieces being spliced together. If you specify
sepas an empty string, the pieces won’t have any character between them.


11.1.4 sprintf()........................................................


The callsprintf(...)assembles a string from parts in a formatted manner.
Here’s a simple example:



i<-8
s <- sprintf("the square of %d is %d",i,i^2)
s
[1] "the square of 8 is 64"



The name of the function is intended to evokestring printfor “printing”
to a string rather than to the screen. Here, we are printing to the strings.
What are we printing? The function says to first print “the square of”
and then print the decimal value ofi. (The termdecimalhere means in the
base-10 number system, not that there will be a decimal point in the result.)
The result is the string"the square of 8 is 64."


11.1.5 substr().........................................................


The callsubstr(x,start,stop)returns the substring in the given character
position rangestart:stopin the given stringx. Here’s an example:



substring("Equator",3,5)
[1] "uat"



11.1.6 strsplit()........................................................


The callstrsplit(x,split)splits a stringxinto an R list of substrings based on
another stringsplitinx. Here’s an example:



strsplit("6-16-2011",split="-")
[[1]]
[1] "6" "16" "2011"



11.1.7 regexpr().......................................................


The callregexpr(pattern,text)finds the character position of the first instance
ofpatternwithintext, as in this example:



regexpr("uat","Equator")
[1] 3



String Manipulation 253
Free download pdf