In R, a string is a sequence of characters enclosed in quotes. Strings are used to store and manipulate text data.
You can create strings using either single quotes ' '
or double quotes " "
:
str1 <- "Hello, World!" str2 <- 'R Programming'
Use typeof()
or class()
to check the data type:
typeof(str1) # "character" class(str1) # "character"
paste()
or paste0()
.nchar()
.substr()
or substring()
.toupper()
and tolower()
.trimws()
.# Concatenation with space greeting <- paste("Hello", "R", "World!") print(greeting) # "Hello R World!" # Concatenation without space greeting2 <- paste0("Hello", "R", "World!") print(greeting2) # "HelloRWorld!" # Length of a string len <- nchar(greeting) print(len) # 13 # Extract substring (from position 1 to 5) sub_str <- substr(greeting, 1, 5) print(sub_str) # "Hello" # Convert to uppercase upper_str <- toupper(greeting) print(upper_str) # "HELLO R WORLD!" # Convert to lowercase lower_str <- tolower(greeting) print(lower_str) # "hello r world!" # Trim whitespace str_with_spaces <- " R is awesome " trimmed_str <- trimws(str_with_spaces) print(trimmed_str) # "R is awesome"
To include special characters like quotes inside strings, use the backslash \\
as an escape character:
quote_str <- "She said, \"R is great!\"" print(quote_str) # She said, "R is great!"
paste()
and paste0()
for concatenation.nchar()
, substr()
, toupper()
, tolower()
, and trimws()
for string manipulation.\\
.Try the following:
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!