R Tutorial



R STRINGS


Strings in R

In R, a string is a sequence of characters enclosed in quotes. Strings are used to store and manipulate text data.

Creating Strings

You can create strings using either single quotes ' ' or double quotes " ":

str1 <- "Hello, World!"
str2 <- 'R Programming'
  

Checking Type and Class

Use typeof() or class() to check the data type:

typeof(str1)    # "character"
class(str1)     # "character"
  

Common String Operations

  • Concatenation: Combine strings using paste() or paste0().
  • Length: Number of characters using nchar().
  • Substring: Extract parts using substr() or substring().
  • Case Conversion: Use toupper() and tolower().
  • Trimming: Remove leading/trailing spaces with trimws().

Examples of String Operations

# 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"
  

Using Escape Characters

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!"
  

Summary

  • Strings in R are sequences of characters enclosed in quotes.
  • Use paste() and paste0() for concatenation.
  • Use functions like nchar(), substr(), toupper(), tolower(), and trimws() for string manipulation.
  • Escape special characters with \\.

Practice Exercise

Try the following:

  • Create two strings and concatenate them with a space.
  • Extract a substring from the concatenated string.
  • Convert the concatenated string to uppercase.
  • Print a string that includes double quotes using escape characters.

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review