The easiest way to format numbers as percentages in R is to use the percent() function from the scales package. This function uses the following syntax:
percent(x, accuracy = 1)
where:
- x: The object to format as a percentage.
- accuracy: A number to round to. For example, use .01 to round to two decimal places.
This tutorial provides several examples of how to use this function in practice.
Example 1: Format Percentages in a Vector
The following code shows how to format numbers as percentages in a vector:
library(scales) #create data data <- c(.3, .7, .14, .18, .22, .78) #format numbers as percentages percent(data, accuracy = 1) [1] "30%" "70%" "14%" "18%" "22%" "78%" #format numbers as percentages with one decimal place percent(data, accuracy = 0.1) [1] "30.0%" "70.0%" "14.0%" "18.0%" "22.0%" "78.0%" #format numbers as percentages with two decimal places percent(data, accuracy = 0.01) [1] "30.00%" "70.00%" "14.00%" "18.00%" "22.00%" "78.00%"
Example 2: Format Percentages in a Data Frame Column
The following code shows how to format numbers as percentages in a column of a data frame:
library(scales)
#create data frame
df = data.frame(region = c('A', 'B', 'C', 'D'),
growth = c(.3, .7, .14, .18))
#view data frame
df
region growth
1 A 0.30
2 B 0.70
3 C 0.14
4 D 0.18
#format numbers as percentages in growth column
df$growth <- percent(df$growth, accuracy=1)
#view updated data frame
df
region growth
1 A 30%
2 B 70%
3 C 14%
4 D 18%
Example 3: Format Percentages in Multiple Data Frame Columns
The following code shows how to format numbers as percentages in multiple columns of a data frame:
library(scales)
#create data frame
df = data.frame(region = c('A', 'B', 'C', 'D'),
growth = c(.3, .7, .14, .18),
trend = c(.04, .09, .22, .25))
#view data frame
df
region growth trend
1 A 0.30 0.04
2 B 0.70 0.09
3 C 0.14 0.22
4 D 0.18 0.25
#format numbers as percentages in growth and trend columns
df[2:3] <- sapply(df[2:3], function(x) percent(x, accuracy=1))
#view updated data frame
df
region growth trend
1 A 30% 4%
2 B 70% 9%
3 C 14% 22%
4 D 18% 25%
You can find more R tutorials on this page.