Yes. In R, use the base function strsplit() to split a string at a chosen separator: for example, strsplit("red,green,blue", ",", fixed = TRUE)[[1]] returns the three words as a character vector. The result is a list when you give the function one or more input strings, so the right way to retrieve the pieces depends on whether you are splitting one string or many.
The basic R string-splitting function
strsplit() is part of base R, so you do not need to install a package. Its basic form is strsplit(x, split): x is the character string or vector of strings, and split describes where each string should be divided. The function returns a list with one element per input string. Each element is a character vector containing that string’s pieces.
text <- "red,green,blue"
parts <- strsplit(text, ",", fixed = TRUE)
parts[[1]]
The final line prints a character vector containing "red", "green", and "blue". The double brackets matter: parts[1] returns a one-element list, while parts[[1]] extracts the character vector inside it. This list structure is useful when the input has several strings, because each original string can produce a different number of pieces.
Choose a literal separator or a pattern
By default, split is treated as a regular expression, not necessarily as an ordinary literal character. For a simple delimiter such as a comma, semicolon, or slash, setting fixed = TRUE makes the intent clear and avoids interpreting punctuation as pattern syntax.
strsplit("one|two|three", "|", fixed = TRUE)[[1]]
strsplit("one;two,three", "[;,]")[[1]]
The first call uses a literal vertical bar. In the second, the regular expression [;,] means “match either a semicolon or a comma,” so both characters act as separators. Regular expressions are useful when the input has several possible delimiters or a pattern such as repeated whitespace. For a literal period, use fixed = TRUE; otherwise a period in a regular expression matches any character.
The main arguments worth knowing are:
x: the input character vector.split: the separator or regular-expression pattern.fixed = TRUE: match the separator literally rather than as a regular expression.perl = TRUE: use Perl-compatible regular-expression behavior when you need its pattern features.useBytes = TRUE: operate on bytes rather than using R’s usual character-aware handling; this is a specialized option, not a routine way to handle text.
Split one string versus a vector of strings
For a single input, extracting the first list element is usually all you need. For multiple inputs, keep the list if you need to preserve which pieces came from which original string.
lines <- c("Ada,Lovelace", "Grace,Hopper")
parts <- strsplit(lines, ",", fixed = TRUE)
parts[[1]]
parts[[2]]
Here parts[[1]] contains the two pieces from the first name, and parts[[2]] contains the two pieces from the second. A common mistake is to use unlist(parts) automatically. That combines every piece into one vector and discards the list boundaries, making it harder to tell which input produced each value. Use it only when flattening is actually what you want.
If you deliberately want one long vector, you can remove names as well:
all_parts <- unlist(parts, use.names = FALSE)
When the pieces need to remain grouped, the list is already a suitable structure. You can inspect how many pieces each input produced with lengths(parts). Unequal counts are normal: one line might contain one separator and another might contain several. If you are building a table with one row per piece, retain an identifier for the source string rather than assuming every list element has the same length.
Splitting on whitespace and several delimiters
Whitespace can include spaces, tabs, and line breaks. A pattern such as [[:space:]]+ matches one or more whitespace characters, which prevents a run of spaces from generating empty pieces between words. Trimming first also removes whitespace at the start and end of the input.
sentence <- " split these words "
words <- strsplit(trimws(sentence), "[[:space:]]+")[[1]]
The result is the words "split", "these", and "words". This is different from splitting on a single literal space: with a single-space separator, repeated spaces can leave empty strings among the results. If preserving the original spacing or exact field positions matters, do not trim or collapse whitespace without considering what information that would remove.
A character class can match any one of several separators. For example, [,;|] matches a comma, semicolon, or vertical bar. That is handy for loosely structured text, but it is not a general-purpose CSV parser. Quoted CSV fields can contain commas that are data rather than delimiters, so use a CSV-reading function such as read.csv() for an actual CSV file instead of splitting each line by commas.
Empty strings, missing values, and boundary separators
Splitting has edge cases that affect the shape of the result. An empty separator, written as "", asks strsplit() to split a string into individual characters. That is not the same as splitting on an empty input string, and it is not a reliable way to divide human-perceived symbols such as every emoji: a displayed symbol can consist of multiple Unicode code points.
When a non-empty separator is used on an empty input string, the result for that input is a character vector of length zero. A separator at the beginning can produce an empty first piece. Trailing empty pieces are a notable case: base R’s strsplit() drops empty fields at the end. For example, splitting "a,b," on a comma does not preserve a final empty field in the same way some other languages’ split functions do. If a final blank field has meaning in your data, check the output carefully and choose a parser or approach designed to retain it.
Missing input values are also distinct from empty strings. An empty string is a present value with no characters; NA_character_ means the value is missing. If your data can contain missing values, inspect them explicitly and decide whether to leave them missing, filter them, or handle them separately before splitting. Do not assume that replacing missing values with "" is harmless, because that changes the meaning of the data.
How to choose the right tool
For ordinary text with a known delimiter, base R’s strsplit() is a good default: it is available everywhere in R and returns a list that naturally represents variable-length results. Use fixed = TRUE for a literal delimiter, and a regular expression when the separator is genuinely a pattern. For one input, extract with [[1]]; for several inputs, decide whether to keep the groups or flatten them.
The stringr package offers str_split(), with a naming style consistent with other functions in that package. It also returns a list by default, so switching packages does not remove the need to understand the result’s structure. If you are already using the tidyverse, it may fit your workflow. For structured files, use a format-aware reader instead: read.csv() for CSV data, or an appropriate tabular-data reader for tab-delimited records. A delimiter split is not a substitute for parsing quotes, escapes, or other file-format rules.
If your goal is to put the first and second pieces into separate columns, splitting is only part of the task. You must also decide what to do when a row has too few or too many pieces, whether whitespace should be removed, and whether separators can occur inside quoted values. Those decisions depend on the data, so preserve the original input until you have checked the output against representative examples.
Common errors and practical checks
Several small checks can prevent confusing results. First, confirm the separator: a regular-expression metacharacter may behave differently from a literal character. Second, check whether each input produced the expected number of parts. Third, inspect leading, repeated, and trailing separators, as well as missing inputs. A short diagnostic is often more useful than assuming every row follows the ideal case.
parts <- strsplit(c("a,b", "c", "d,e,f"), ",", fixed = TRUE)
lengths(parts)
parts
This example returns counts of two, one, and three. It illustrates why the output is a list rather than a rectangular character matrix: rows can have different numbers of fields. Avoid converting to a matrix until you have decided how to handle those uneven lengths. Also remember that strsplit() divides text; it does not convert the pieces into numbers, dates, or other data types. Convert and validate those values separately after splitting.
Frequently Asked Questions
How do I split a string by a comma in R?
Use strsplit("a,b,c", ",", fixed = TRUE)[[1]]. The result is a character vector with three elements. For a vector of input strings, omit [[1]] to keep the list of results.
Why does strsplit() return a list?
Each input string can produce a different number of pieces. A list allows R to keep each string’s results together even when those lengths differ. Use double brackets to extract one result, or unlist() only if you intentionally want to combine them.
How do I split on a period or another special character?
For a literal special character, set fixed = TRUE, as in strsplit("a.b", ".", fixed = TRUE)[[1]]. Without that setting, the period is regular-expression syntax and matches any character.
How can I split on spaces when there may be several?
Use strsplit(trimws(text), "[[:space:]]+")[[1]]. The pattern matches one or more whitespace characters, and trimws() removes whitespace around the outside. Skip trimming if boundary whitespace is meaningful.
Does strsplit() keep an empty field after a final delimiter?
No: base R drops trailing empty pieces. If the final blank field carries meaning, test the parsing approach against that case and use a format-aware reader or another method that preserves the fields you need.
Related
- EF Core AsSplitQuery: How It Works and When to Use It
- SOLIDWORKS Split: How to Divide a Solid Body
- Split Part in SOLIDWORKS: How to Divide and Save Bodies
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Schedule an Email Reminder in Outlook: Step-by-StepTo get a reminder to follow up on an Outlook email, flag the message and set a reminder…
- Excel Sales Tracking Template by Product: How to Build OneThe best way to track sales by product in Excel is to use a template that combines a…
- How to Group Rows in JMPTo group rows in a JMP data table, select the rows you want to keep together, then choose…
- How to Find Errors in Excel: A Practical Workbook GuideTo find formula errors in Excel for Microsoft 365 on Windows, choose Formulas > Error Checking to review…
- Excel Import CSV as Text: Keep Every Value UnchangedTo import a CSV into Excel as text, use Data > From Text/CSV, choose the file, select Transform…
- Cash Flow Forecast Template Excel: Free OptionsYes—free cash flow forecast templates for Excel are available from Microsoft Create and other spreadsheet providers, although the…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.