10 pairbind() and pairbind_df()

The function pairbind() appends two datasets’ rows in a pairwise fashion. In other words, it appends the 1st row of the first dataset with the 1st row of the second dataset, the 2nd row of the first with the 2nd row of the second, and so on. This function can be useful for kable-friendly frequency distribution tables.

The two required inputs are x and y, each being a 2D object (e.g. dataframe, matrix, etc). The output is a matrix.

The function pairbind_df() accomplishes the same as pairbind() except that the output is a data frame.

10.0.1 Creating a kable-friendly Frequency Distribution Table

library(tidyverse) # For Data management 
## Warning: package 'tidyverse' was built under R version 3.6.2
## Warning: package 'ggplot2' was built under R version 3.6.3
## Warning: package 'tibble' was built under R version 3.6.3
## Warning: package 'dplyr' was built under R version 3.6.3
## Warning: package 'forcats' was built under R version 3.6.3
library(magrittr)  # For the update assignment pipe operator %<>%
library(knitr)     # For kable().
## Warning: package 'knitr' was built under R version 3.6.3
library(kableExtra)# For other kable functions.
## Warning: package 'kableExtra' was built under R version 3.6.3
# Frequencies
freq_df <- with(diamonds, table(color, clarity)) %>%
  as.data.frame() %>%
  spread(NCOL(.) - 1, NCOL(.)) %>%
  mutate(Total = apply(.[, 2:NCOL(.)], 1, sum))

# Percentages
 prop_df <- freq_df 
 prop_df[, 2:NCOL(prop_df)] <- prop_df[, 2:NCOL(prop_df)]/prop_df$Total
 prop_df[, 2:NCOL(prop_df)] %<>% 
   map_df(~ paste0(round(.x*100), '%'))
  freq_df %<>% 
  format(., big.mark = ',', scientific = FALSE) %>%
  map_df(as.character)

# Output
prop_df %<>% map_df(as.character)

pb <- pairbind_df(freq_df, prop_df)

pb %>%
  kable(booktabs = TRUE) %>%
  kable_styling(full_width = TRUE) %>%
  collapse_rows(1, valign = 'top', latex_hline = 'major')
color I1 SI2 SI1 VS2 VS1 VVS2 VVS1 IF Total
D 42 1,370 2,083 1,697 705 553 252 73 6,775
1% 20% 31% 25% 10% 8% 4% 1% 100%
E 102 1,713 2,426 2,470 1,281 991 656 158 9,797
1% 17% 25% 25% 13% 10% 7% 2% 100%
F 143 1,609 2,131 2,201 1,364 975 734 385 9,542
1% 17% 22% 23% 14% 10% 8% 4% 100%
G 150 1,548 1,976 2,347 2,148 1,443 999 681 11,292
1% 14% 17% 21% 19% 13% 9% 6% 100%
H 162 1,563 2,275 1,643 1,169 608 585 299 8,304
2% 19% 27% 20% 14% 7% 7% 4% 100%
I 92 912 1,424 1,169 962 365 355 143 5,422
2% 17% 26% 22% 18% 7% 7% 3% 100%
J 50 479 750 731 542 131 74 51 2,808
2% 17% 27% 26% 19% 5% 3% 2% 100%