Skip to contents

This function takes a tibble with a multi-response column, where responses are separated by a delimiter (e.g., commas), and splits it into separate columns. Each new column corresponds to a unique response option, and the values indicate whether that option was selected ("Selected") or not ("Not Selected").

Usage

srv_separate_mr(data, col, sep = ",", label_prefix = "")

Arguments

data

A data frame (preferably a tibble) containing the data to be processed.

col

A tidyselect expression to select a multi-response column to be separated.

sep

A character string that defines the delimiter used to separate the responses within the multi-response column. The default value is ",".

label_prefix

An optional character string to be used as a prefix for the labels of the new columns. The default is an empty string ("").

Value

A tibble with the following changes:

  • The original multi-response column is removed.

  • New columns are added for each unique response option. Each new column indicates whether the corresponding option was selected ("Selected") or not ("Not Selected").

  • The labels of the new columns are set to the unique response values, optionally prefixed by the label_prefix if provided.

Note

The function is designed to handle simple multi-response columns where responses are separated by a consistent delimiter.

Examples

# Simple example with a comma-separated multi-response column
library(tibble)
data <- tibble(id = 1:3, choices = c("A,B", "A", "B,C"))
srv_separate_mr(data, "choices")
#> # A tibble: 3 × 4
#>      id choices_1    choices_2    choices_3   
#>   <int> <fct>        <fct>        <fct>       
#> 1     1 Selected     Selected     Not Selected
#> 2     2 Selected     Not Selected Not Selected
#> 3     3 Not Selected Selected     Selected    

# It is also possible to use tidyselect
srv_separate_mr(data, choices)
#> # A tibble: 3 × 4
#>      id choices_1    choices_2    choices_3   
#>   <int> <fct>        <fct>        <fct>       
#> 1     1 Selected     Selected     Not Selected
#> 2     2 Selected     Not Selected Not Selected
#> 3     3 Not Selected Selected     Selected    

# Example with a different delimiter
data <- tibble(id = 1:3, choices = c("A|B", "A", "B|C"))
srv_separate_mr(data, "choices", sep = "|")
#> # A tibble: 3 × 4
#>      id choices_1    choices_2    choices_3   
#>   <int> <fct>        <fct>        <fct>       
#> 1     1 Selected     Selected     Not Selected
#> 2     2 Selected     Not Selected Not Selected
#> 3     3 Not Selected Selected     Selected    

# Example with a label prefix
data <- tibble(id = 1:3, choices = c("A,B", "A", "B,C"))
resp <- srv_separate_mr(data, "choices", label_prefix = "Selected option: ")
resp$choices_1
#> [1] Selected     Selected     Not Selected
#> attr(,"label")
#> [1] Selected option: A
#> Levels: Selected Not Selected