How To Convert Numeric To String In R

In data analysis and reporting, it is frequently necessary to convert numerical quantities to strings. For many activities in R, such as formatting data for visualisation, getting data ready for export, and working with strings for data analysis, the ability to transform numeric values into strings is a key skill. Thankfully, R offers a variety of easy, effective, complicated, and adaptable ways for converting numbers to strings.

By the time you finish reading this article, you’ll know exactly how to convert numbers to strings in R and be able to use this knowledge for your own data analysis and reporting requirements.

Why convert numeric to string in R

Here are a few reasons why numeric-to-string conversion is required:

  • Working with strings is frequently more versatile and effective than dealing only with numerical numbers.
  • For accurate data display and visualisation, string formatting is essential.
  • Doing a conversion from numeric to string improves compatibility with R functions that need character input.
  • Character data may make sorting and categorising data simpler, especially when the data is alphanumeric.
  • Only when both are in string format is it possible to concatenate string values with numeric numbers.
  • All data may need to be in string format to export data in a text format.

Various Approaches to convert numeric to String in R:

  • as.character() Function
  • paste() and paste0() Functions
  • sprintf() Function 
  • format() Function
  • Using a Loop

1. as.character() Function

This function converts any R object to its character representation, including numeric values.

Code:

# Numeric vector
num_vec <- c(1, 2, 3)

# Convert numeric to string using as.character()
str_vec <- as.character(num_vec)

# Output
str_vec

Output:

[1] "1" "2" "3"

Explanation:

  • The as.character() function is a built-in function in R that converts any R object to its character representation.
  • This function can be used to convert numeric values to their string representation. In the example, we have defined a numeric vector num_vec and then converted it to a character vector str_vec using the as.character() function.
  • The resulting output is a character vector containing the string representation of the original numeric values.

2. paste() and paste0() Functions

These functions can concatenate two or more character strings, including strings that represent numeric values.

Code:

# Numeric values
num1 <- 10
num2 <- 20.5

# Using paste()
str1 <- paste("The value of num1 is:", num1, "and the value of num2 is:", num2)

# Output
str1

Output:

[1] "The value of num1 is: 10 and the value of num2 is: 20.5"

Explanation:

  • The paste() and paste0() functions are used to concatenate two or more character strings in R.
  • These functions can also be used to concatenate strings that represent numeric values. In the example, we have defined two numeric values num1 and num2, and then used the paste() function to concatenate them with some additional string text.
  • Also used the paste0() function to concatenate the same numeric values without any separators between them.
  • The resulting output for both examples is a character vector containing the concatenated string.

3. sprintf() Function 

This function allows for more flexible formatting of the output string, including specifying the number of decimal places and adding leading zeros.

Code:

# Numeric value
num <- 10.5

# Convert numeric to string using sprintf()
str <- sprintf("The value of num is: %05.2f", num)

# Output
str

Output:

][1] "The value of num is: 10.50"

Explanation:

  • The sprintf() function in R allows for more flexible formatting of output strings.
  • This function uses a format string to specify how the output string should be formatted.
  • In the example, we have defined a numeric value num and then used the sprintf() function to convert it to a string representation with two decimal places and leading zeros.
  • The resulting output is a character vector containing the formatted string.

4. format() Function

This function converts numeric to string and provides additional formatting options, such as specifying the number of decimal places and adding commas.

Code:

format()
str <- format(num, big.mark=",")

# Output
str

Output:

[1] "1,234,567.89"

Explanation:

  • The format() function in R is used to format numeric values as strings.
  • This function provides additional formatting options, such as adding commas and specifying the number of decimal places.
  • In the example, we have defined a numeric value num and then used the format() function to convert it to a string representation with commas added.
  • ]The resulting output is a character vector containing the formatted string.

5. Using a Loop

In some cases, converting numeric to the string may involve looping through a data structure and applying a conversion function to each element.

Code:


# Numeric matrix
num_mat <- matrix(c(1, 2, 3, 4, 5, 6), ncol=2)

# Loop through matrix and convert numeric to string using as.character()
str_mat <- matrix(nrow=nrow(num_mat), ncol=ncol(num_mat))
for (i in 1:nrow(num_mat)) {
 for (j in 1:ncol(num_mat)) {
   str_mat[i, j] <- as.character(num_mat[i, j])
 }
}

# Output
str_mat

Output:

[,1] [,2]
[1,] "1"  "4"
[2,] "2"  "5"
[3,] "3"  "6"

Explanation:

  • In some cases, converting numeric to the string may involve looping through a data structure and applying a conversion function to each element.
  • In the example, we have defined a numeric matrix num_mat and then used a nested loop to iterate through each element of the matrix and convert it to a string using the as.character() function.
  • The resulting output is a matrix with the same dimensions as the original numeric matrix, but with each element converted to a string representation.

Best Approach:

The best approach overall for converting numeric to string in R is the as.character() function. This is because:

  • It is a built-in function in R, which means it is readily available and easy to use.
  • It is simple and efficient.
  • The as.character() function is a simple and efficient way to convert numeric values to strings in R.
  • It is also versatile, as it can be used on a single value or an entire vector of values.

Sample Questions:

Sample Problem 1:

How much interest will be earned on an initial deposit of $10,000 with an interest rate of 3.5% per annum compounded monthly after one year?

Solution:

  • Suppose you are a financial analyst working for a bank, and you need to calculate the interest earned on a customer’s savings account.
  • The customer has deposited $10,000 into their account, which earns an annual interest rate of 3.5%. The bank compounds the interest monthly.
  • Calculate the total interest earned over one year, and display the result as a string with two decimal places.
  • Define the initial deposit and interest rate. We then calculate the monthly interest rate by dividing the annual interest rate by 12, and determine the number of compounding periods (12 for monthly compounding over one year).
  • Then use the formula for compound interest to calculate the final balance after one year and subtract the initial deposit to obtain the total interest earned.
  • Use the format() function to convert the interest earned to a string with two decimal places, and then use the cat() function to display the result as a string.

Code:

# Define the initial deposit and interest rate
deposit <- 10000
interest_rate <- 0.035

# Calculate the monthly interest rate and number of compounding periods
monthly_rate <- interest_rate/12
n_periods <- 12

# Calculate the final balance after one year
final_balance <- deposit * (1 + monthly_rate)^n_periods

# Calculate the total interest earned
interest_earned <- final_balance - deposit

# Convert the interest earned to a string with two decimal places
interest_string <- format(interest_earned, nsmall = 2)

# Print the result
cat("The total interest earned is $", interest_string, ".", sep = "")

Output:

The total interest earned is $352.03.

Sample Problem 2:

What is the concentration of a solution containing 0.125 grams of solute dissolved in 50 millilitres of the solution? Express the concentration in grams per litre.

Solution:

  • Suppose you are a scientist experimenting in a lab, and you need to calculate the concentration of a solution.
  • You have measured the mass of the solute and the volume of the solution. The mass of the solute is 0.125 grams, and the volume of the solution is 50 milliliters.
  • Calculate the concentration of the solution in units of grams per liter, and display the result as a string with four decimal places.
  • Define the mass of the solute and the volume of the solution. We convert the volume from milliliters to liters by dividing by 1000.
  • Then calculate the concentration of the solution in units of grams per liter by dividing the mass of the solute by the volume of the solution in liters.
  • Use the sprintf() function to convert the concentration to a string with four decimal places, and then use the cat() function to display the result as a string.
  • Converting the numeric concentration to a string with four decimal places helps ensure the accuracy of the calculation, which is important in scientific experiments.

Code:

# Define the mass of the solute and volume of the solution
mass <- 0.125 # grams
volume <- 50 # milliliters

# Convert volume to liters
volume_l <- volume/1000

# Calculate the concentration in grams per liter
conc <- mass/volume_l

# Convert the concentration to a string with four decimal places using sprintf()
conc_string <- sprintf("%.4f", conc)

# Print the result
cat("The concentration of the solution is", conc_string, "grams per liter.")

Output:

The concentration of the solution is 2.5000 grams per liter.

Sample Problem 3:

What are the average temperatures in Fahrenheit for each of the past 5 years based on the given temperature data in Celsius?

Solution:

  • The first few lines of code are the same as in the original code. We define a variable num_years to store the years to calculate the average temperature.
  • Create an empty numeric vector avg_temps with a length equal to num_years.
  • This vector will be used to store the average temperatures.
  • Use a for loop to iterate over the years. Inside the loop, calculate the current year’s temperature data’s starting and ending indices using the formula (2 * i) – 1 and (2 * i).
  • Then use these indices to extract the temperature data for the current year and calculate its average temperature using the mean() function.
  • The average temperature is stored in the avg_temps vector. After the loop, we use the format() function to convert the average temperatures to strings with two decimal places and store them in a new vector year_strings.
  • Finally, use another for loop to print the results for each year. Use the cat() function inside the loop to print the year number, average temperature string, and Fahrenheit symbol.

Code:

# Define temperature data for the last 10 years
temp_data <- c(12.3, 14.5, 13.6, 11.8, 13.2, 12.1, 15.2, 14.8, 13.9, 12.7)

# Convert temperature data to Fahrenheit
temp_f <- (temp_data * 1.8) + 32

# Define the number of years
num_years <- 5

# Create an empty vector to store the average temperatures
avg_temps <- numeric(num_years)

# Calculate average temperature for each year using a loop
for (i in 1:num_years) {
 start_index <- (2 * i) - 1
 end_index <- start_index + 1
 avg_temps[i] <- mean(temp_f[start_index:end_index])
}

# Convert average temperatures to strings with two decimal places
year_strings <- format(avg_temps, nsmall = 2)

# Print the results
for (i in 1:num_years) {
 cat("Average temperature for year", i, ":", year_strings[i], "°F\n")
}

Output:

Average temperature for year 1: 55.22 °F
Average temperature for year 2: 53.96 °F
Average temperature for year 3: 57.38 °F
Average temperature for year 4: 56.42 °F
Average temperature for year 5: 55.04 °F

Sample problem 4:

How to convert a numeric dataset of blood pressure readings into a character vector with units using R?

Solution:

  • Suppose you have a dataset of patient blood pressure readings, represented as numeric values in millimeters of mercury (mmHg).
  • To convert these values to strings and add the units “mmHg” to the end of each value. use the paste0() function to concatenate the numeric values and the string ” mmHg”.
  • First convert the numeric values to character strings using as.character().
  • The resulting blood_pressure_string variable contains the blood pressure readings as strings with units.
  • This type of conversion can be useful in medical data analysis for maintaining precision and accuracy in measurements and analyses.

Code:

# Create a sample dataset of blood pressure readings
blood_pressure <- c(120, 130, 135, 140, 125)

# Convert numeric values to strings and add "mmHg" units
blood_pressure_string <- paste0(as.character(blood_pressure), " mmHg")

# Print the result
blood_pressure_string

Output:

[1] "120 mmHg" "130 mmHg" "135 mmHg" "140 mmHg" "125 mmHg"

Sample Problem 5:

How to convert exam scores to letter grades using a grading scale in R programming?

Solution:

  • Suppose we have a dataset of exam scores for a class of students, represented as numeric values.
  • To convert these scores to strings and add a letter grade based on a grading scale (A=90-100, B=80-89, C=70-79, D=60-69, F=0-59).
  • Define a grading scale as a named list, and use a custom function get_grade() to assign a letter grade to each numeric score.
  • Then use paste0() to concatenate the numeric values, the string ” (“, the letter grade, and the closing parenthesis.
  • The resulting score_strings variable contains each score as a string with a letter grade.
  • This type of conversion can be useful in statistical analysis for accurately summarizing and presenting data.
  • By converting numeric values to strings with letter grades, we can quickly and easily communicate the performance of a group of individuals or compare different groups.
# Create a sample dataset of exam scores
scores <- c(85, 73, 92, 65, 78, 81, 97)

# Create a grading scale as a named list
grading_scale <- list(A = c(90, 100), B = c(80, 89), C = c(70, 79), D = c(60, 69), F = c(0, 59))

# Function to assign letter grades based on grading scale
get_grade <- function(x, grading_scale) {
 for (grade in names(grading_scale)) {
   if (x >= grading_scale[[grade]][1] && x <= grading_scale[[grade]][2]) {
     return(grade)
   }
 }
}

Output:

# Convert numeric values to strings with letter grades
score_strings <- paste0(as.character(scores), " (", sapply(scores, get_grade, grading_scale), ")")

# Print the result
score_strings

Conclusion:

In conclusion, converting numeric to string is a crucial task in various domains, including finance, science, climate analysis, medical analysis, and statistical analysis, where accuracy and precision are vital.

Using the sprintf() function is the most efficient and straightforward. The process helps reduce memory consumption, saves space, and simplifies mathematical operations on large datasets.

By providing practical examples and sample code for each scenario, we have demonstrated the usefulness of converting numeric to string in R for data analysis.