Quantcast
Viewing all articles
Browse latest Browse all 106

RStudio using kable to print a table of multiple variable sums and percentages

I'd like to create a table using kable that knits to Word. I can create the table I want for one variable, but I'd like to present multiple variables in one table.Data:

library(tidyr)library(knitr)library(tidyverse)df <- data.frame(             rating1=c("Very important", "Important", "Unimportant", "Unimportant", "Very important", "Important"),             rating2=c("Important", "Important", "Neutral", "Unimportant", "Unimportant", " Very unimportant"),             rating3=c( "Unimportant", "Unimportant", " Very unimportant", "Neutral", "Unimportant", " Very unimportant"))

Here's what I have so far for one variable, and I'd like the same for multiple variables. But I'd like the layout to be different: variable names as rows on the left hand side, and then columns for the n and % for each of the 5 answers options (11 columns in total).

df %>%  filter(!is.na(rating1)) %>%  count(rating1, sort = TRUE) %>%  mutate(percent = round(100 * (n / sum(n)), 1)) %>%  arrange(desc(n)) %>%  add_row(rating1 = "**Total**", n = sum(.$n), percent = 100) %>%  kable(align = "lcc", col.names = c('**Rating 1**', '**n**', '**%**'))

Viewing all articles
Browse latest Browse all 106

Trending Articles