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:
Syntax
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
text <- "Hello, R World!"
cat(substr(text, 1, 5), "\n")
cat(substr(text, 8, 8), "\n")
Login to try C/C++/Java/PHP code in the editor
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
- Using 0 as the start position, when R strings start at position 1.
- Confusing
substr(text, 1, 5)with start and length, when the third argument is the end position. - Trying to change a string by index like
text[1] <- "J", which replaces the whole string; usesubstr(text, 1, 1) <- "J".
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: