Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

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 strhead <- function(s,n) {
+   if(n

and start using them:

> strhead("abc", 1)
[1] "a"
[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.