Learn R Programming

numform (version 0.6.4)

alignment: Detect Column Alignment

Description

Many of the specialized functions in numform can change the type of the data from numeric to character causing the table formatting functions in various add-on packages to improperly align the elements. This function passes the columns with a regular expression to detect alignment regardless of column class.

Usage

alignment(
  x,
  left = "left",
  right = ifelse(left == "l", "r", "right"),
  additional.numeric = paste0("^(((–|\\+))|(([0-9.%-]+)",
    "|(\\$?\\s*\\d+[KBM])))|(NaN|NA|Inf)$"),
  sep = NULL,
  ...
)

Arguments

x

A data.frame.

left

A value to print for left aligned columns.

right

A value to print for right aligned columns. If left = "l" right will default to "r" otherwise defaults to "right".

additional.numeric

An additional regex to consider as numeric. To turn off this feature use additional.numeric = NULL.

sep

A string to collapse the vector on.

ignored.

Value

Returns a vector of lefts and rights or a string (if sep is not NULL.

Examples

Run this code
# NOT RUN {
CO <- CO2
CO[] <- lapply(CO, as.character)
alignment(CO)
head(CO2)


# }
# NOT RUN {
library(dplyr)
library(pander)
library(xtable)

set.seed(10)
dat <- data_frame(
    Team = rep(c("West Coast", "East Coast"), each = 4),
    Year = rep(2012:2015, 2),
    YearStart = round(rnorm(8, 2e6, 1e6) + sample(1:10/100, 8, TRUE), 2),
    Won = round(rnorm(8, 4e5, 2e5) + sample(1:10/100, 8, TRUE), 2),
    Lost = round(rnorm(8, 4.4e5, 2e5) + sample(1:10/100, 8, TRUE), 2),
    WinLossRate = Won/Lost,
    PropWon = Won/YearStart,
    PropLost = Lost/YearStart
)


dat %>%
    group_by(Team) %>%
    mutate(
        `%ΔWinLoss` = fv_percent_diff(WinLossRate, 0),
        `ΔWinLoss` = f_sign(Won - Lost, '<b>+</b>', '<b>–</b>')

    ) %>%
    ungroup() %>%
    mutate_at(vars(Won:Lost), .funs = ff_denom(relative = -1, prefix = '$')) %>%
    mutate_at(vars(PropWon, PropLost), .funs = ff_prop2percent(digits = 0)) %>%
    mutate(
        YearStart = f_denom(YearStart, 1, prefix = '$'),
        Team = fv_runs(Team),
        WinLossRate = f_num(WinLossRate, 1)
    ) %>%
    as.data.frame() %>%
    pander::pander(split.tables = Inf, justify = alignment(.))


alignment(CO, 'l', 'r')

CO %>%
    xtable(align = c('', alignment(CO, 'l', 'r'))) %>%
    print(include.rownames = FALSE)


CO %>%
    xtable(align = c('', alignment(CO, 'l|', 'r|'))) %>%
    print(include.rownames = FALSE)
# }

Run the code above in your browser using DataLab