11.1.1 grep().........................................................
The callgrep(pattern,x)searches for a specified substringpatternin a
vectorxof strings. Ifxhasnelements—that is, it containsnstrings—then
grep(pattern,x)will return a vector of length up ton. Each element of this
vector will be the index inxat which a match ofpatternas a substring of
x[i]) was found.
Here’s an example of usinggrep:
> grep("Pole",c("Equator","North Pole","South Pole"))
[1]23
> grep("pole",c("Equator","North Pole","South Pole"))
integer(0)
In the first case, the string"Pole"was found in elements 2 and 3 of the
second argument, hence the output (2,3). In the second case, string"pole"
was not found anywhere, so an empty vector was returned.
11.1.2 nchar().........................................................
The callnchar(x)finds the length of a stringx. Here’s an example:
> nchar("South Pole")
[1] 10
The string"South Pole"was found to have 10 characters. C program-
mers, take note: There is no NULL character terminating R strings.
Also note that the results ofnchar()will be unpredictable ifxis
not in character mode. For instance,nchar(NA)turns out to be 2, and
nchar(factor("abc"))is 1. For more consistent results on nonstring objects,
use Hadley Wickham’sstringrpackage on CRAN.
11.1.3 paste().........................................................
The callpaste(...)concatenates several strings, returning the result in one
long string. Here are some examples:
> paste("North","Pole")
[1] "North Pole"
> paste("North","Pole",sep="")
[1] "NorthPole"
> paste("North","Pole",sep=".")
[1] "North.Pole"
> paste("North","and","South","Poles")
[1] "North and South Poles"
252 Chapter 11