Learn R Programming

janitor (version 0.3.1)

ns_to_percents: Convert a numeric data.frame to row-, column-, or totals-wise percentages.

Description

This function excludes the first column of the input data.frame, assuming that it contains a descriptive variable.

Usage

ns_to_percents(dat, denom = "row", na.rm = TRUE, total_n = NULL)

Arguments

dat

a data.frame with row names in the first column and numeric values in all other columns.

denom

the denominator to use for calculating percentages. One of "row", "col", or "all".

na.rm

should missing values (including NaN) be omitted from the calculations?

total_n

an optional number to use as the denominator when calculating table-level percentages (when denom = "all"). Supply this if your input data.frame dat has values that would throw off the denominator if they were included, e.g., if there's a totals row appended to the bottom of the table.

Value

Returns a data.frame of percentages, expressed as numeric values between 0 and 1.

Examples

Run this code
# NOT RUN {
mtcars %>%
  crosstab(am, cyl) %>%
  ns_to_percents(denom = "all")
  
  # when total_n is needed
  mtcars %>%
  crosstab(am, cyl) %>%
  adorn_totals("row") %>% # add a totals row that should not be included in the denominator
  ns_to_percents(denom = "all", total_n = nrow(mtcars)) # specify correct denominator
# }

Run the code above in your browser using DataLab