A key aspect is the argumentfixed=TRUE. Without it, the splitting argu-
ment.(calledsplitin the list ofstrsplit()’s formal arguments) would have
been treated as a regular expression. Without settingfixed=TRUE,strsplit()
would have just separated all the letters.
Of course, we could also escape the period, as follows:
1 testsuffix <- function(fn,suff) {
2 parts <- strsplit(fn,"\\.")
3 nparts <- length(parts[[1]])
4 return(parts[[1]][nparts] == suff)
5 }
Let’s check to see if it still works.
> testsuffix("x.y.abc","abc")
[1] TRUE
Here’s another way to do the suffix-test code that’s a bit more involved
but a good illustration:
1 testsuffix <- function(fn,suff) {
2 ncf <- nchar(fn) # nchar() gives the string length
3 # determine where the period would start if suff is the suffix in fn
4 dotpos <- ncf - nchar(suff) + 1
5 # now check that suff is there
6 return(substr(fn,dotpos,ncf)==suff)
7 }
Let’s look at the call tosubstr()here, again withfn = "x.ac"and
suff = "abc". In this case,dotposwill be 1, which means there should be a
period at the first character infnif there is anabcsuffix. The call tosubstr()
then becomessubstr("x.ac",1,4), which extracts the substring in character
positions 1 through 4 ofx.ac. That substring will bex.ac, which is notabc,
so the filename’s suffix is found not to be the latter.
11.2.2 Extended Example: Forming Filenames............................
Suppose we want to create five files,q1.pdfthroughq5.pdf, consisting of
histograms of 100 random N(0,i^2 ) variates. We could execute the follow-
ing code:
1 for (i in 1:5) {
2 fname <- paste("q",i,".pdf")
3 pdf(fname)
4 hist(rnorm(100,sd=i))
5 dev.off()
6 }
256 Chapter 11