chr_to_var: Convert a string / character variable into a labelled double...

View source: R/chr_to_var.R

chr_to_varR Documentation

Convert a string / character variable into a labelled double variable, using a pre-specified set of variable and value label mappings.

Description

This function takes a string variable and converts it into a labelled double variable, using value label mappings (lab_str, lab_num) and variable labels (var_label) provided by the user.

Usage

chr_to_var(var, lab_str, lab_num, var_label, na = "<N/A>", wrap = 100)

Arguments

var

string vector containing the variable

lab_str

string vector containing the labels for the variable. The lengths and values must be an exact match of the variable in var.

lab_num

numeric vector matching the labels provided in lab_str. The length of lab_num must be the same as lab_str, and the order is used to determine the mapping.

var_label

string to be used as the variable label, passed through to set_varl().

na

string to replace missing values with as a value label. Defaults to "<N/A>". Set to NULL to not replace missing values.

wrap

numeric value to apply a text wrap to value labels for plotting aesthetics. The numeric value determines the number of minimum characters before the next space before adding a new line (⁠\n⁠). Defaults to 100.

Details

This function is a wrapper around several other surveytoolbox functions:

  • create_named_list()

  • set_vall()

  • set_varl()

Value

a labelled double variable

Examples

var1 <- c("Yes", "No", "Not sure")
lab1 <- c(1, 0, 99)
q1_var <- sample(var1, 100, replace = TRUE)

# Convert to labelled double
chr_to_var(
  var = q1_var,
  lab_str = var1,
  lab_num = lab1,
  var_label = c("Have you come across this product previously?")
)

## Example with missing values
# Generate variable with missing values
var1 <- c("Yes", "No", NA) 
q1_var <- sample(var1, 100, replace = TRUE)

# Variable and value labels
var1b <- c("Yes", "No", "<N/A>")
lab1 <- c(1, 0, 99)

# Convert to labelled double
chr_to_var(
  var = q1_var,
  lab_str = var1b,
  lab_num = lab1,
  var_label = c("Have you come across this product previously?")
)


martinctc/surveytools documentation built on Nov. 21, 2024, 10:48 p.m.