R Strings

R Strings

Strings are primarily used for securely storing and manipulating text data.

A string is written entirely inside double quotes "" or single quotes ''.


Multi-line Strings

Unlike many other languages, R allows you to create massive multi-line strings very easily.

You simply press "Enter" while inside the quotes, and R securely captures the line breaks!

This makes importing raw textual paragraphs completely painless.


String Length and Searching

To find the exact number of characters in a string, you use the nchar() function.

To check if a specific word exists inside a string, you use the grepl() function.

grepl() returns a logical TRUE if it finds the word, and FALSE if it does not!

String Functions Example:

str <- "Hello World!"
# Find the string length
print(nchar(str)) # Outputs 12
# Search the string for the word "World"
print(grepl("World", str)) # Outputs TRUE

Concatenating Strings

To join two or more separate strings together, you use the paste() function.

It intelligently combines strings side-by-side, adding spaces between them automatically.

This is incredibly helpful for dynamically generating textual reports based on data!


Exercise 1 of 2

?

Which function calculates and returns the exact number of characters within a string?

Exercise 2 of 2

?

Which function searches a string and returns TRUE if a specified word is found?