In R, a string is text stored as a value in a character vector. You create one by putting text in single or double quotation marks, such as "hello"; R has no separate scalar string type, so even one string is a character vector of length one.
What a string means in R
R calls its text data type character. A character vector can contain one text value or many, and each value is commonly called a string. For example, "hello" is a one-element character vector, while c("hello", "goodbye") has two elements. The function typeof() reports "character" for either object.
This terminology matters when reading R code and help pages: functions often refer to character vectors rather than strings. The vector model also explains why functions such as paste() can work across several text values at once. Unlike languages with distinct string and character types, R does not use a separate type for a single letter; "x" is still a character vector containing one string.
Text is a basic part of data work. Column names, labels, dates imported as text, search terms, file paths, and messages may all be represented as character data. Knowing how R stores and transforms that data helps prevent problems when cleaning, matching, or displaying it.
Creating strings and escaping characters
Either single or double quotes can mark the beginning and end of an ordinary string. The opening and closing marks must match. These expressions both create the same text:
"R language"'R language'
Use the other kind of quote inside a string when convenient: "it's R" or 'She said "hello"'. If the text contains the same quote mark used to delimit it, escape that character with a backslash. For example, "She said \"hello\"" includes quotation marks around hello. A backslash also introduces special characters: \n means a newline, \t a tab, and \\ a literal backslash.
For paths on Windows, forward slashes often avoid the need to escape backslashes: "C:/reports/data.csv". If you write backslashes, double them, as in "C:\\reports\\data.csv". In R 4.0.0 and later, raw string literals can make some patterns easier to read. For example, r"(C:\reports\data.csv)" treats the backslashes as literal characters, subject to the raw-string delimiter rules.
An empty string, "", is a valid character value containing no text. It is not the same as NA_character_, which represents missing character data. That distinction affects tests and results: an empty field may mean a known blank value, while NA means the value is unavailable or unknown.
Character vectors, conversion, and missing values
Use c() to combine string values into a vector. R can also convert other basic values to character with as.character(). For instance, as.character(42) returns the text "42"; it does not return the number 42. This conversion is useful for labels and output, but arithmetic on the resulting text will not behave like arithmetic on a number without converting it back.
When a vector mixes character values with numbers, R generally converts the numbers to character so the vector has one consistent type. For example, c("item", 3) produces character data, with the number represented as text. This can surprise someone expecting a mixed-type vector. Check with str() or typeof() when an imported column or combined vector does not behave as expected.
Use NA_character_ when you want to explicitly create a missing character value. is.na(x) checks which elements are missing. Do not test for missingness by comparing with the text "NA": those are different values. The text may literally be a two-letter label, whereas a missing value has no known character content. Empty strings also require their own check, such as x == "", with care if x may contain missing values.
Inspecting and measuring text
Several small functions help inspect character data before modifying it. class(x) and typeof(x) describe its type, length(x) counts vector elements, and nchar(x) counts the characters in each element. These counts answer different questions: for c("cat", "elephant"), length() is 2, while nchar() returns 3 and 8.
By default, nchar() counts characters, not bytes. Those measures can differ for non-ASCII text because a character may take more than one byte in a particular encoding. You can ask for a byte count with nchar(x, type = "bytes"), but that is usually not the count a person means when asking how many letters a string has. Unicode grapheme clusters add another subtlety: a displayed symbol may be represented by multiple code points, so a technical character count is not always the same as the number of visible symbols.
For a quick look at a vector, use print() or str(). R displays quotation marks around character values to distinguish text from other output. Those marks are part of the display, not necessarily characters stored in the string itself. Use writeLines() when you want to print text without the usual quoted representation; newlines inside the string are then visible as line breaks.
Joining and formatting strings
Base R provides paste() and paste0() to join text. paste() inserts a separator, a space by default; paste0() joins without one. For example, paste("R", "programming") returns "R programming", while paste0("R", "programming") returns "Rprogramming". Set the separator explicitly when the desired punctuation or spacing should be clear.
Both functions recycle shorter inputs when combining vectors, following R’s vectorization rules. Thus paste0(c("file", "image"), 1:2) produces "file1" and "image2". If you provide collapse, the resulting vector is joined into one string: paste(c("red", "green", "blue"), collapse = ", ") returns "red, green, blue". This is different from sep, which separates pieces within each result.
For controlled formatting, sprintf() uses format placeholders. For example, sprintf("Score: %d%%", 87) produces "Score: 87%"; %d represents an integer and %% inserts a literal percent sign. Formatting is handy for reports and messages, but it does not automatically make arbitrary text safe for every context, such as HTML or SQL. Use a method designed for the destination when output must be escaped securely.
Searching, extracting, and replacing
Base R includes functions for common text operations. grepl() returns a logical result indicating whether a pattern occurs; grep() returns matching indices by default. For literal matching rather than regular-expression matching, use fixed = TRUE. For example, grepl(".", x, fixed = TRUE) searches for a period, while a period in a regular expression normally matches any single character.
Use sub() to replace the first match in each string and gsub() to replace all matches. Both interpret the pattern as a regular expression unless configured otherwise. To extract text by position, substr(x, start, stop) uses positions counted from 1, and its start and stop positions are inclusive. For splitting around a pattern, strsplit() returns a list because different input strings can split into different numbers of pieces.
Regular expressions are compact patterns for describing text. For example, grepl("^[A-Z]", x) checks whether a string begins with an uppercase English letter: ^ marks the start and [A-Z] is a range. Patterns can be powerful, but special characters such as ., *, and ? have meanings that may need escaping or literal matching. For a simple search term containing punctuation, fixed = TRUE is often less error-prone.
Base R or the stringr package?
Base R is enough for many everyday tasks and requires no additional package. Functions such as paste(), nchar(), grepl(), sub(), and strsplit() are available in a standard R installation. Their names and argument styles vary, so consulting the help page for a specific function is useful when building a longer text-processing workflow.
The stringr package, part of the tidyverse, offers a consistent family of functions whose names begin with str_, including str_detect(), str_replace(), and str_sub(). It works naturally with vectors and has helpers for choosing regular-expression, fixed, or boundary matching. Install it once with install.packages("stringr"), then load it with library(stringr). Its regular-expression handling is based on ICU, while base R uses its own regular-expression interfaces; edge cases and supported syntax can therefore differ. Choose the package that fits the project and be consistent, especially when patterns rely on less-common regex features.
Encoding, Unicode, and common problems
Text can contain characters beyond basic English letters, including accented characters, scripts from many languages, and emoji. R tracks encoding information for character data, and functions that read or write files may need the correct encoding specified. A file displayed as unreadable symbols is often an encoding mismatch rather than a flaw in the string operation. When importing or exporting text, check the file’s actual encoding and the relevant function’s encoding options instead of assuming every file uses the same one.
Common mistakes include confusing a string’s printed quotes with its contents, forgetting that backslashes introduce escapes, and treating missing values as ordinary text. Another frequent error is using length() to count letters; it counts vector elements. Use nchar() for the length of each string. Similarly, a regular expression may interpret punctuation as an operator when the goal was a literal search. Test patterns on a few representative examples, including empty strings, missing values, punctuation, and non-English text.
- Check the type and structure with
str(x)before applying a transformation. - Use
is.na(x)to identify missing values rather than comparing to the text"NA". - Choose
fixed = TRUEwhen a base R search should treat punctuation literally. - Test encoding-sensitive text after both reading and writing the file.
Frequently Asked Questions
Does R have a string data type?
R’s text type is called character. A single string is a character vector with one element; there is no separate scalar string type.
What is the difference between a string and a character vector?
A string is one text value. A character vector is an R object containing one or more such values, so a single string is also a one-element character vector.
How do I join strings in R?
Use paste() to join values with a separator, or paste0() to join them without a separator. Use the collapse argument when you want to combine a whole vector into one string.
How do I check whether text contains a word?
Use grepl() for a logical answer, or grep() when you want matching positions. Set fixed = TRUE if the search text should be treated literally rather than as a regular expression.
Is an empty string the same as NA in R?
No. "" is a known value containing no characters, while NA_character_ represents missing character data. Use is.na() to test for missingness.
Related
- Graphing the Line y = -1: Points, Slope, and Examples
- How to Split Data in Google Sheets
- SOLIDWORKS Split Part: Create Two Separate Bodies Guide
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Excel Care Group: Homes, Services and What to KnowExcelcare, often described as the Excel Care Group, is a UK care provider that operates care homes and…
- Excel Page Break Keyboard Shortcut and How to Use ItIn Excel for Microsoft 365 on Windows, press Alt, P, B, I in sequence to insert a manual…
- How to Present PowerPoint and See Your Speaker NotesTo present PowerPoint while keeping your notes visible, open the deck in the desktop app, select Slide Show…
- How to Split a Cell in Excel: Easy Ways to Separate TextThe easiest way to split text in an Excel cell is to select it, then choose Data >…
- Remove Duplicates in Excel: Keyboard ShortcutIn Excel for Microsoft 365 on Windows, select a cell in your data and press Alt, then A,…
- Does Google Sheets Have XLOOKUP? How to Use ItYes. Google Sheets has a built-in XLOOKUP function that finds a value in one range and returns the…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.