formatC Function in R (3 Examples)

 

In this article, I’ll demonstrate how to format number using the formatC function in R.

The article will consist of three examples for the application of the formatC function. More precisely, the content is structured as follows:

Let’s get started.

 

Constructing Example Data

The data below is used as basement for this R programming tutorial.

set.seed(3459643)                 # Create example data
x <- rnorm(5)
x                                 # Print example data
# [1] -2.08465048  0.42994609  1.36221077 -0.07050613  1.64029672

The previous RStudio console output shows the structure of our example data – We have created a random numeric vector.

 

Example 1: Basic Application of formatC() Function

In this example, I’ll demonstrate how to apply the formatC function to a data object containing numbers.

If we want to use the default specifications of the formatC function, we can apply the function as shown below:

formatC(x)                        # Apply formatC function
# [1] "-2.085"   "0.4299"   "1.362"    "-0.07051" "1.64"

As you can see, the formatC function has returned our numbers converted to the character class and with fewer digits.

 

Example 2: Specify Number of Digits Using formatC() Function

In Example 2, I’ll illustrate how to specify the number of digits that should be returned by the formatC function.

Have a look at the following R code:

formatC(x, digits = 2)            # Specify digits
# [1] "-2.1"   "0.43"   "1.4"    "-0.071" "1.6"

As you can see, the number of digits has been changed. Note that each number contains two values that are unequal to zero.

 

Example 3: Specify Decimal Mark Using formatC() Function

In Example 3, I’ll explain how to change the decimal mark from point to comma using the formatC function.

For this task, we can apply the decimal.mark argument as shown below:

formatC(x, decimal.mark = ",")    # Specify decimal.mark
# [1] "-2,085"   "0,4299"   "1,362"    "-0,07051" "1,64"

The decimal point of our input data has been changed to a comma separator.

 

Video, Further Resources & Summary

I have recently published a video on my YouTube channel, which shows the R programming syntax of this tutorial. You can find the video below.

 

The YouTube video will be added soon.

 

Furthermore, you could read some of the other R tutorials that I have published on my website.

 

In this article, I have shown how to apply the formatC function to use C-style formats for numbers in the R programming language. Don’t hesitate to let me know in the comments, if you have any further questions.

 

Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.


Leave a Reply

Your email address will not be published.

Fill out this field
Fill out this field
Please enter a valid email address.

Menu
Top