I have dplyr::recode
some factors and I am looking for a clean way to make LaTeX table where new and old categories, i.e. levels, are compared.
Here's an illustration of the issues using cyl
from `mtcars. First some packages,
# install.packages("tidyverse", "stargazer","reporttools")
library(tidyverse)
and the data I intend to use,
mcr <- mtcars %>% select(cyl) %>% as_tibble()
mcr %>% print(n=5)
#> # A tibble: 32 x 1
#> cyl
#> * <dbl>
#> 1 6.00
#> 2 6.00
#> 3 4.00
#> 4 6.00
#> 5 8.00
#> # ... with 27 more rows
Now, I create two new factor, one with 3 categories, cyl_3col
, and one with two, cyl_is_red
, i.e.:
mcr_col <- mcr %>% as_tibble() %>%
mutate(cyl_3col = factor(cyl, levels = c(4, 6, 8),labels = c("red", "blue", "green")),
cyl_is_red = recode(cyl_3col, .default = 'is not red', 'red' = 'is red'))
mcr_col %>% print(n=5)
#> # A tibble: 32 x 3
#> cyl cyl_3col cyl_is_red
#> <dbl> <fct> <fct>
#> 1 6.00 blue is not red
#> 2 6.00 blue is not red
#> 3 4.00 red is red
#> 4 6.00 blue is not red
#> 5 8.00 green is not red
#> # ... with 27 more rows
Now, I would like to show how the categories in cyl_3col
and cyl_is_red
are related.
Maybe something like this is better,
#> cyl_is_red cyl_3col
#> is red
#> red
#> is not red
#> blue
#> green
possible something like this, I imagine the is not red
category spanning two rows with \multirow{}
or something like it.
#> cyl_3col cyl_is_red
#> 1 red is red
#> 2 blue is not red
#> 3 green ----------
using stargazer or possibly some other TeX tool. I am very open as to how I can best show the recoding. I assume there's some smart way to code this thought out by someone who came before me?
I've used something like mcr_col %>% count(cyl_3col, cyl_is_red)
for now, but I don't think it's really working.
"\n"
, then useknitr::kable(x, format = "latex")
– Nehemiah