← Back to R Course | Chapter 6: Strings | Lesson 3 of 7

substr

substr cuts a slice out of a piece of text between two positions, like using scissors on a ribbon. You say where to start and where to stop.

In this page:

  1. substr
Syntax
r
substr(x, start, stop)

substr

substr(x, start, stop) extracts a substring between the given character positions, inclusive on both ends, using 1-based indexing. substr() can also be used on the left side of an assignment to replace part of a string in place.

This is R's built-in way to slice strings by position.

Note: Unlike many languages, substr()'s stop index is inclusive -- substr("hello", 1, 3) gives "hel", including position 3.

Example: substr

markup
text <- "Hello, R World!"

cat(substr(text, 1, 5), "\n")
cat(substr(text, 8, 8), "\n")
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Using 0 as the start position, when R strings start at position 1.
  2. Confusing substr(text, 1, 5) with start and length, when the third argument is the end position.
  3. Trying to change a string by index like text[1] <- "J", which replaces the whole string; use substr(text, 1, 1) <- "J".
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.