strsplit
strsplit chops a piece of text into parts wherever a separator appears, like cutting a sandwich at each line. A sentence can become a list of words this way.
In this page:
Syntax
parts <- strsplit(x, split)
parts[[1]]
strsplit
strsplit(x, split) splits a string into pieces wherever the separator pattern occurs, returning a list (since each input string could split into a different number of pieces).
Accessing the first result requires indexing into the list, like strsplit(x, ",")[[1]]. This is the standard way to parse delimited text like CSV rows.
Note:
strsplit() always returns a list, even for a single string input -- use [[1]] to get the character vector of pieces out.
Example: strsplit
csv_line <- "apple,banana,cherry"
parts <- strsplit(csv_line, ",")[[1]]
print(parts)
cat("Second item:", parts[2], "\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
- Treating the result as a vector and writing
parts[2]directly, whenstrsplitreturns a list and you need[[1]]first. - Splitting on a special regex character like
"."or"|", which matches unexpectedly; usefixed = TRUE. - Expecting an empty piece at the end of a string ending in the separator, when a trailing empty string is dropped.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: