head and tail for strings

October 2, 2010

(This article was first published on factbased, and kindly contributed to R-bloggers)

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.

To leave a comment for the author, please follow the link and comment on their blog: factbased.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...

If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.