R String formatting

String formatting in R is done via the sprintf function. An easy example of code that prepares a string using a variable value is provided below:

R




# Create two variables with values
x <- 42
y <- 3.14159
 
# Format a string with the two variable values
result <- sprintf("The answer is %d, and pi is %.2f.", x, y)
 
# Print the result
print(result)


Output

[1] "John is 35 years old and 1.80 meters tall."

In this example, we format a string with two decimal places using the%d format specifier for the integer value x and the%.2f format specifier for the floating-point value y. The prepared string is saved in the variable result before being written to the console using the print function. You should see the output when you run this code. The solution is 42, and pi is 3.14, which is the formatted string with x and y values substituted for the format specifiers.

R Strings

Strings are a bunch of character variables. It is a one-dimensional array of characters. One or more characters enclosed in a pair of matching single or double quotes can be considered a string in R. Strings in R Programming represent textual content and can contain numbers, spaces, and special characters. An empty string is represented by using “. R Strings are always stored as double-quoted values. A double-quoted string can contain single quotes within it. Single-quoted strings can’t contain single quotes. Similarly, double quotes can’t be surrounded by double quotes.

Similar Reads

Creation of String in R

R Strings can be created by assigning character values to a variable. These strings can be further concatenated by using various functions and methods to form a big string....

Length of String

...

Accessing portions of an R string

The length of strings indicates the number of characters present in the string. The function str_length() belonging to the ‘string’ package or nchar() inbuilt function of R can be used to determine the length of strings in R....

Case Conversion

...

Concatenation of R Strings

...

R String formatting

The individual characters of a string can be extracted from a string by using the indexing methods of a string. There are two R’s inbuilt functions in order to access both the single character as well as the substrings of the string....

Updating R strings

...

Contact Us