format_checkbox: Format Checkbox Columns

View source: R/format_checkbox.R

format_checkboxR Documentation

Format Checkbox Columns

Description

Modify a data frame representing a 'select all that apply' style survey question. Makes implicit negative responses explicit while keeping non-responses as is.

Usage

format_checkbox(df, relabel = TRUE)

Arguments

df

A data frame

relabel

Should the value label be set as the variable label?

Details

The steps taken are:

  1. Set the variable label as the (presumably singular) value label if relabel = TRUE

  2. Find the observations that are missing across all columns

  3. Remove value labels, replace missing values with zeroes

  4. Replace values with NA for completely missing observations

Value

A data frame

Author(s)

Sven Halvorson (svenpubmail@gmail.com)

Examples

set.seed(0)
checkbox_example = tibble(
  TREATMENT = rep(c('treat', 'control'), each = 20),
  Q1 = sample(c(1, NA), size = 40, replace = TRUE),
  Q2 = sample(c(1, NA), size = 40, replace = TRUE),
  Q3 = sample(c(1, NA), size = 40, replace = TRUE)
)
# Note first & third rows are all missing

# Set some value labels:
for(i in 1:3){
  lab = 1
  names(lab) = LETTERS[i]
  expss::val_lab(checkbox_example[paste0('Q',i)]) = lab
}

# Make a new dataframe of just the formatted checkbox questions:
formatted_checkbox = checkbox_example %>%
  select(all_of(paste0('Q', 1:3))) %>%
  format_checkbox()

attributes(formatted_checkbox[['Q1']])

# Also can do assignment for a chunk of the data frame but it's a little trickier
checkbox_example[,paste0('Q', 1:3)] = format_checkbox(checkbox_example[,paste0('Q', 1:3)])
checkbox_example

svenhalvorson/SvenR documentation built on Aug. 25, 2023, 1:31 p.m.