# NOT RUN {
library(dplyr)
f <- fmt(n = c(7, 19, 2), type = "row", pct = c(0.25, 0.679, 0.07))
f
# To get the currently displayed field :
get_num(f)
# To modify the currently displayed field :
set_num(f, c(1, 0, 0))
# See all the underlying fields of a fmt vector (a data frame with a number of rows
# equal to the length of the vector) :
vctrs::vec_data(f)
# To get the numbers of digits :
vctrs::field(f, "digits")
f$digits
# To get the count :
vctrs::field(f, "n")
f$n
# To get the display :
vctrs::field(f, "display")
f$display
# To modify a field, you can use `dplyr::mutate` on the fmt vector,
# referring to the names of the columns of the underlying data.frame (`vctrs::vec_data`) :
vctrs::`field<-`(f, "pct", c(1, 0, 0))
mutate(f, pct = c(1, 0, 0))
# See all the attributes of a fmt vector :
attributes(f)
# To modify the "type" attribute of a fmt vector :
set_type(f, "col")
# To modify the "color" attribute of a fmt vector :
set_color(f, "contrib")
tabs <- tab(starwars, sex, hair_color, gender, na = "drop", pct = "row",
rare_to_other = TRUE, n_min = 5)
# To identify the total columns, and work with them :
is_totcol(tabs)
tabs %>% mutate(across(where(is_totcol), ~ "total column"))
# To identify the total rows, and work with them :
is_totrow(tabs)
tabs %>%
mutate(across(
where(is_fmt),
~ if_else(is_totrow(.), true = "into_total_row", false = "normal_cell")
))
# To identify the total tables, and work with them :
tottabs <- is_tottab(tabs)
tabs %>% tibble::add_column(tottabs) %>%
mutate(total = if_else(tottabs, "part of a total table", "normal cell"))
# To access the displayed numbers, as numeric vectors :
tabs %>% mutate(across(where(is_fmt), get_num))
# To access the displayed numbers, as character vectors (without colors) :
tabs %>% mutate(across(where(is_fmt), format))
# To access the (non-displayed) differences of the cells percentages from totals :
tabs %>% mutate(across(where(is_fmt), ~ vctrs::field(., "diff")))
# To do more complex operations, like creating a new column with standard deviation and
# print it with 2 decimals, use `dplyr::mutate` on all the fmt columns of a table :
tab_num(forcats::gss_cat, race, c(age, tvhours), marital, digits = 1L, comp = "all") |>
dplyr::mutate(dplyr::across( #Mutate over the whole table.
c(age, tvhours),
~ dplyr::mutate(., #Mutate over each fmt vector's underlying data.frame.
var = sqrt(var),
display = "var",
digits = 2L) |>
set_color("no"),
.names = "{.col}_sd"
))
# }
Run the code above in your browser using DataLab