Number to Percentage in R, I’ll describe how to express numerical numbers in % using the R programming language on this page.

Let’s go to the R syntax right away:

The following example vector serves as the foundation for this tutorial’s examples:

# design a sample vector x <- c(11.2, 12.5, 10.103, 37, 30.1501)

Our sample vector, x, has four different numerical values in it.

I’ll demonstrate how to translate these numerical numbers into percentages in the tutorial on R programming that follows.

### Example 1: Use a user-defined function to format a number as a percentage

There is no function for converting numbers to percentages in the R programming language’s default installation.

However, as demonstrated below, we can develop our own function for this task.

percent <- function(x, digits = 2, format = "f", ...) { paste0(formatC(x * 100, format = format, digits = digits, ...), "%") }

We can now utilise our user-defined function in the manner shown below:

percent(x) [1] "1120.00%" "1250.00%" "1010.30%" "3700.00%" "3015.01%"

The output of the RStudio console shows that our input vector was formatted into percentages, as you can see.

Notably, the character class rather than the numeric class is present in the output vector.

### Example 2: Use scales to format a number as a percentage package

We constructed a user-defined function in Example 1 to express numbers as percentages. For the R programming language, there are numerous add-on packages that offer related functionalities.

For instance, such a function is offered by the scales package.

Installing and loading the scales package into R is next:

install.packages("scales") library("scales")

Now, we can utilise the scales package’s percent function as follows:

scales::percent(x) "1 120%" "1 250%" "1 010%" "3 700%" "3 015%"

Note that the output is automatically rounded to one decimal digit by the % command of the scales package. However, you can modify that in the function options.

How to perform the MANOVA test in R? – Data Science Tutorials

### Example: Format a number as a percentage with a formattable package

The formattable package is another one that offers a function for converting an integer to a percentage format.

Installing and loading the package now.

install.packages("formattable") library("formattable")

Similar to the scales package’s function in Example 2, the pertinent function of the format package is similarly known as percent().

The formattable package’s percent function can be used as demonstrated below:

formattable::percent(x)

[1] 1120.00% 1250.00% 1010.30% 3700.00% 3015.01%

The percent function of the formattable package displays two digits after the decimal point, as can be seen from the RStudio console output.

How to perform Rolling Average in R Â»