This article describes how to go from two variables of mutually exclusive data...
...to a single variable of merged data:
This scenario can occur when you have different segments getting asked a different set of survey questions.
Two or more variables with mutually exclusive data.
1. Select Anything > Data > Variables > New > Custom Code > R - Numeric.
2. Update the Name and Label on the object inspector under Properties > GENERAL.
3. Paste the below under Properties > R CODE:
# join variables together in same set
df = data.frame(q1_1,q1_2)
# create merged column
m = df %>% unite("Merged", na.rm = TRUE, remove = FALSE)
m = m[,1]
# combine code frame
labels = unique(m)
# assign code frame
merged = factor(m, levels = labels)
- The above code groups the input variables together. In this example, the variables are referenced via variable name which is found in the object inspector under Properties > GENERAL > Name.
- We then use tidyr's unite function to merge the data into a single column.
- Using the unique function, we store all the unique value labels from both variables. This ensures if there are any differences, such as in this example with Refuse to answer and Don't care, that they both get recorded correctly.
- Finally, we set the unique labels as the categories in the new merged variable.
4. Change Properties > Structure to Nominal: Mutually exclusive categories.