Learn R Programming

guideR (version 0.8.1)

combine_answers: Combine answers of a multiple answers question

Description

Considering a multiple answers question coded as several binary variables (one per item), create a new variable (list column or character) combining all positive answers. If defined, use variable labels (see examples).

Usage

combine_answers(data, answers, into, value = NULL, sep = NULL)

Arguments

data

A data frame, data frame extension (e.g. a tibble), or a survey design object.

answers

<tidy-select> List of variables identifying the different answers of the question.

into

Names of new variables to create as character vector.

value

Value indicating a positive answer. By default, will use the maximum observed value and will display a message.

sep

An optional character string to separate the results and return a character. If NULL, return a list column (see examples).

Examples

Run this code
d <-
  dplyr::tibble(
    q1a = sample(c("y", "n"), size = 200, replace = TRUE),
    q1b = sample(c("y", "n", "n", NA), size = 200, replace = TRUE),
    q1c = sample(c("y", "y", "n"), size = 200, replace = TRUE),
    q1d = sample("n", size = 200, replace = TRUE)
  )

d |> combine_answers(q1a:q1d, into = "combined")
d |> combine_answers(q1a:q1d, into = "combined", sep = ", ", value = "y")
d |> combine_answers(q1a:q1d, into = "combined", sep = " | ", value = "n")

# works with survey objects
d |>
  srvyr::as_survey() |>
  combine_answers(q1a:q1d, into = "combined")

Run the code above in your browser using DataLab