· r-2

R: substr - Getting a vector of positions

I recently found myself writing an R script to extract parts of a string based on a beginning and end index which is reasonably easy using the substr function:


> substr("mark loves graphs", 0, 4)
[1] "mark"

But what if we have a vector of start and end positions?


> substr("mark loves graphs", c(0, 6), c(4, 10))
[1] "mark"

Hmmm that didn't work as I expected! It turns out we actually need to use the substring function instead which wasn't initially obvious to me on reading the documentation:


> substring("mark loves graphs", c(0, 6, 12), c(4, 10, 17))
[1] "mark"   "loves"  "graphs"

Easy when you know how!

  • LinkedIn
  • Tumblr
  • Reddit
  • Google+
  • Pinterest
  • Pocket