2010-10-02

head and tail for strings

The functions head and tail are very useful for working with lists, tables, data frames and even functions.
But they do not work on strings. It is easy to define such functions


> strtail <- function(s,n=1) {
+ if(n<0)
+ substring(s,1-n)
+ else
+ substring(s,nchar(s)-n+1)
+ }
> strhead <- function(s,n) {
+ if(n<0)
+ substr(s,1,nchar(s)+n)
+ else
+ substr(s,1,n)
+ }

and start using them:


> strhead("abc", 1)
[1] "a"
> strhead("abc", -1)
[1] "ab"
> strtail("abc", 1)
[1] "c"
> strtail("abc", -1)
[1] "bc"

It is not a good idea to name these functions head.character and tail.character because this
has unexpected effects if applied to a vector of strings.

Other useful string functions are defined in the the
stringr package.