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

substr

In this page:

  1. substr

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")
🔒

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.