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.

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.

Value

a labelled double variable

Details

This function is a wrapper around several other surveytoolbox functions:

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?")
)
#> <labelled<double>[100]>: Have you come across this product previously?
#>   [1] 99 99 99  1  1 99  0  0  0  1  0  0  0  1 99 99  1  0  1 99  0  0  1  1  0
#>  [26]  1  1  0  1  1 99  0  0 99  1  0 99 99  1  0 99  0  0  1 99  0  0  0  0 99
#>  [51]  1 99  1  1  1  0  1  1 99  1 99 99  0  1  1  0  1  0  0  0  0  1  0  0 99
#>  [76]  0 99  1 99 99  0 99  1 99  0 99  1  1  1  0  1  1  1 99  1  1  1  1  0  1
#> 
#> Labels:
#>  value    label
#>      1      Yes
#>      0       No
#>     99 Not sure

## 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?")
)
#> <labelled<double>[100]>: Have you come across this product previously?
#>   [1]  0  0  1 99 99  0 99 99 99  1  0 99 99 99  0  1 99 99  0  1  1  0 99  1  1
#>  [26]  1  0 99  0  0 99  0  1  0 99  1  0  0  1  0 99 99  1 99  0  0  1  1  0  1
#>  [51]  0  0  0  0  0  1  1 99  0  0 99 99 99 99  1  0  0  1 99  1  1  0  1 99 99
#>  [76]  1  0  0  1  0  1  0 99  0 99  0  0 99 99 99  1 99 99 99 99  0 99 99 99 99
#> 
#> Labels:
#>  value label
#>      1   Yes
#>      0    No
#>     99 <N/A>