In this tutorial, we will learn how to add currency symbols, like US dollars, Euro, UK pound, Indian Rupee to columns of a table using the R package gt.
Let us load gt package to make beautiful tables and tidyverse.
library(tidyverse) library(gt)
First we will create a simple dataframe/tibble with stock prices of a few companies in USD.
tibble(symbol=c("GOOG", "META", "MSFT"), price = c(168, 465, 425)) ## # A tibble: 3 × 2 ## symbol price ## <chr> <dbl> ## 1 GOOG 168 ## 2 META 465 ## 3 MSFT 425
With gt() we can simply convert the dataframe into a simple table.
tibble(symbol=c("GOOG", "META", "MSFT"), price = c(168, 465, 425)) |> gt()
Add US Dollar symbol to columns in table with fmt_currency() in gt
With gt package, we can automatically add US dollar symbol $ to numerical columns using fmt_currency() function.
tibble(symbol=c("GOOG", "META", "MSFT"), price = c(168, 465, 425)) |> gt() |> fmt_currency()
In the example below, fmt_currency() has identified the price column as a column to add US dollar symbol.
Add US Dollar symbol to specific columns in gt
We can add US dollar symbol to a specific column using fmt_currency() function in gt package. Now we have to specify the name of the column that we want to add dollar symbol using the columns argument as shown below.
tibble(symbol=c("GOOG", "META", "MSFT"), price = c(168, 465, 425)) |> gt() |> fmt_currency(columns=price)
How to add world currency symbols to columns with gt
We can find the list of all supported currency symbols available with gt package using info_currencies() function as shown below.
info_currencies(type = "symbol")
This will list the available world currency symbols and how it looks in a table.
Adding multiple currency symbols to columns in a table
In the example below, we show how to add a world currency symbol (Indian rupee symbol) in addition to US dollar symbol. We specify the currency symbol of interest, in this example Indian rupee, using currency argument to fmt_currency() function.
tibble(symbol=c("GOOG", "META", "MSFT"), price_USD = c(168, 465, 425)) |> mutate(price_INR = price_USD*80) |> gt() |> fmt_currency(columns=price_USD) |> fmt_currency(columns = price_INR, currency="rupee" )