Let’s use a portion of the towny dataset and create a table showing population, density, and land area for 10 municipalities. The land_area_km2 values are in units of square kilometers, however, we’d rather the values were in square miles. We can convert the numeric values while formatting the values with fmt_number() by using unit_conversion() in the scale_by argument since the return value of that is a conversion factor (which is applied to each value by multiplication). The same is done for converting the ‘people per square kilometer’ values in density_2021 to ‘people per square mile’, however, the units to convert are in the denominator so the inverse of the conversion factor must be used.
With a small slice of the gibraltar dataset, let’s display the temperature values in terms of degrees Celsius (present in the data) and as temperatures in degrees Fahrenheit (achievable via conversion). We can duplicate the temp column through cols_add() (naming the new column as temp_f) and when formatting through fmt_integer() we can call unit_conversion() within the scale_by argument to perform this transformation while formatting the values as integers.
gibraltar |> dplyr::filter( date =="2023-05-15", time >="06:00", time <="12:00" ) |> dplyr::select(time, temp) |>gt() |>tab_header(title ="Air Temperature During Late Morning Hours at LXGB Stn.",subtitle ="May 15, 2023" ) |>cols_add(temp_f = temp) |>cols_move(columns = temp_f, after = temp) |>tab_spanner(label ="Temperature",columns =starts_with("temp") ) |>fmt_number(columns = temp,decimals =1 ) |>fmt_integer(columns = temp_f,scale_by =unit_conversion(from ="temperature.C",to ="temperature.F" ) ) |>cols_label(time ="Time",temp ="{{degC}}",temp_f ="{{degF}}" ) |>cols_width(starts_with("temp") ~px(80), time ~px(100) ) |>opt_horizontal_padding(scale =3) |>opt_vertical_padding(scale =0.5) |>opt_align_table_header(align ="left") |>tab_options(heading.title.font.size =px(16))
Air Temperature During Late Morning Hours at LXGB Stn.