R Strings

R string is written within a pair of the single quote or double quotes. Internally, R stores every string within double quote (” “), even when you create them with a single quote (‘ ‘).

Example 1:

Output:

Example 2:

Output:

String Manipulation

There are so many types of functions available for string manipulation:

paste()

In R paste() function is used to concatenate the strings.  In short, we can say that it is used to combine the strings. It can take one or more number of arguments to be combined together.

Syntax:

Arguments:

  • one or more number of arguments (R objects) to be combined
  • sep used to represent any separator between the arguments. It is optional.
  • collapse is used to remove the space in between two strings but not the space within two words of one string.

Example:

Output:

format()

Strings and numbers can be formatted to a specific style using the format() function.

Syntax:

Arguments:

  • x is the vector input or any R object typically numeric
  • digits total number of digits to be displayed
  • nsmall minimum number of digits to the right of the decimal point.
  • scientific to display scientific notation it should be set to TRUE.
  • width indicates the minimum width to be displayed by padding space in the beginning.
  • justify is used to set the display of the string to left, right or center.

Example:

Output:

nchar()

This function is used to count the number of characters including spaces in a string.

Syntax:

Arguments:

  • x is the vector input.

Example 1:

Output:

Example 2:

Output:

toupper()

This function is used to convert string to its upper case.

Syntax:

Arguments:

x is the vector input.

Example:

Output:

tolower()

This function is used to convert string to its lower case.

Syntax:

Arguments:

x is the vector input.

Example:

Output:

substring()

This function is used to extract part of the string.

Syntax:

Arguments:

  • x is the vector input.
  • first is the position of the first character to be extracted.
  • last is the position of the last character to be extracted.

Example:

Output:

replace()

This function is used to replace the values in x with indices given in the list by those given in values.

Syntax:

Arguments:

  • x is the vector input.
  • list indices
  • values replacement value

Example 1:

Output:

Example 2:

Output:

Reference:
https://www.tutorialspoint.com/r/r_strings.htm
https://www.w3schools.in/r/strings/