Force R to Show Scientific Notation (2 Examples)

 

In this tutorial you’ll learn how to show numbers in scientific notation (e.g. 12e-7) in R programming.

The page will contain these topics:

Let’s get started.

 

Creating Example Data

Before all else, let’s construct some example data:

x <- c(31.111, 3.1111, 0.03, 0.031111)    # Create example vector
x                                         # Print example vector
# [1] 31.111000  3.111100  0.030000  0.031111

The previous output of the RStudio console shows that our example data is a numeric vector containing four different values with different size.

As you can see, by default the R programming language shows these numbers without scientific notation.

 

Example 1: Show Number in Scientific Notation Using formatC() Function

This example explains how to use the formatC function to convert our numbers to a scientific notation character string.

Have a look at the following R code and its output:

formatC(x, format = "e")                  # Show in scientific notation
# [1] "3.1111e+01" "3.1111e+00" "3.0000e-02" "3.1111e-02"

As you can see, our numbers are shown in scientific notation. Note that these numbers have the character class instead of the numeric class.

 

Example 2: Show Number in Scientific Notation with Only Two Digits

In Example 2, I’ll explain how to manipulate the number of digits that are shown when displaying number in scientific notation.

For this, we can use the digits argument provided by the formatC function:

formatC(x, format = "e", digits = 2)      # Scientific notation with two digits
# [1] "3.11e+01" "3.11e+00" "3.00e-02" "3.11e-02"

As you can see, the number of digits was reduced to two.

 

Video & Further Resources

Have a look at the following video of my YouTube channel. I explain the R programming codes of this tutorial in the video.

 

 

Furthermore, you may have a look at some of the related tutorials of Statistics Globe.

 

This page has shown how to display numeric values in scientific notation in the R programming language. Tell me about it in the comments section below, if you have additional 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.


2 Comments. Leave new

  • AWESOME Joachim. Thank you I modified your code to use inline_hook which I learned from Pat Schloss’ Riffomonas Project

    library(knitr)
    inline_hook <- function(x){
    # paste0("**", x, "**")
    if(is.numeric(x)){
    formatted <- formatC(x, format="e", digits=2)
    } else{
    formatted <- x
    }
    }

    knit_hooks$set(inline=inline_hook)

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

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

Top