Hi everyone. I'm attempting to create a "topline" of tabulated frequency distributions for a longish survey. I've figured out how to use tabyl and flextable functions to create nicer looking tables, but have been copying and pasting the commands over and over again, replacing only the variable names and renaming the table objects themselves.
Is there a way to repeat this process with code rather than copying and pasting?
I'm new to R and have never posted here before. I've attempted to follow the guidelines outlined on the welcome page, but am open to feedback about how to ask better questions. I've also searched around quite a bit lookking for similar examples, but since it's all quite new for me I need step-by-step guidance and really appreciate the help.
# load libraries
library(tidyverse)
library(janitor)
library(flextable)
library(officer)
# create dataframe with nominal and ordinal data
gender <- c("Male", "Male", "Male", "Male", "Female", "Female", "Female", "Male", "Female")
opinion <- c("Strongly Agree", "Strongly Agree", "Somewhat Agree", "Somewhat Agree", "Neither",
"Neither", "Somewhat Disagree", "Strongly Disagree", "Strongly Disagree")
opinion <- factor(opinion, order = TRUE, levels = c('Strongly Agree','Somewhat Agree', 'Neither',
'Somewhat Disagree', 'Strongly Disagree'))
df <- data.frame(gender, opinion)
# create tables of tabulated frequencies
gender_tbl <- df %>%
tabyl(gender) %>%
adorn_totals() %>%
adorn_pct_formatting(digits = 0, rounding = "half up")
gender_tbl <- flextable(gender_tbl) %>%
set_header_labels(gender = "",
percent = "Percent")
gender_tbl <- width(gender_tbl, width = 2.0)
gender_tbl <- align(gender_tbl, j = 1, align = "left", part = "all")
gender_tbl <- align(gender_tbl, j = 3, align = "right", part = "all")
gender_tbl
# so far, I've been copying and pasting for each of the variables in the survey
# as in below.
opinion_tbl <- df %>%
tabyl(opinion) %>%
adorn_totals() %>%
adorn_pct_formatting(digits = 0, rounding = "half up")
opinion_tbl <- flextable(opinion_tbl) %>%
set_header_labels(opinion = "",
percent = "Percent")
opinion_tbl <- width(opinion_tbl, width = 2.0)
opinion_tbl <- align(opinion_tbl, j = 1, align = "left", part = "all")
opinion_tbl <- align(opinion_tbl, j = 3, align = "right", part = "all")
opinion_tbl