New Variables
The following examples create three types of variables: a binary variable with values of 0 and 1, a categorical variable that is later converted to a factor, and a count variable calculated as the sum of values across rows.
Example 1: Binary Variable
# Example 1: Binary Variable
# Food Insecurity Indicator
table(cchs$food_security, useNA = "ifany")
cchs$food_insecure <- ifelse(cchs$food_security == "Secure", 0, 1)
# Check
table(cchs$food_security, cchs$food_insecure, useNA = "ifany")

Example 2: Categorical Variable
# Example 2: Categorical Variable
# Smoking & Drinking Risk Categories
table(cchs$smoking, useNA = "ifany")
table(cchs$drinking, useNA = "ifany")

cchs$risk <- NA
cchs$risk[cchs$smoking == "Current" & cchs$drinking == "Regular"] <- "Both"
cchs$risk[cchs$smoking == "Current" & cchs$drinking != "Regular"] <- "Smoker"
cchs$risk[cchs$smoking != "Current" & cchs$drinking == "Regular"] <- "Drinker"
cchs$risk[cchs$smoking != "Current" & cchs$drinking != "Regular"] <- "Neither"
# Check
table(cchs$smoking, cchs$drinking, useNA = "ifany")
table(cchs$risk, useNA = "ifany")

# Convert from character to factor
str(cchs$risk)
cchs$risk <- factor(cchs$risk, levels = c("Both", "Smoker", "Drinker", "Neither"))
str(cchs$risk)
table(cchs$risk, useNA = "ifany")

Example 3: Count Variable
# Example 3: Count Variable
# Total Chronic Conditions Reported
cchs$chronic_count <- rowSums(cbind(cchs$diabetes, cchs$hbp, cchs$cholesterol, cchs$mood,
cchs$anxiety, cchs$fatigue, cchs$msk, cchs$cardiovascular),
na.rm = TRUE)
# Check
table(cchs$chronic_count, useNA = "ifany")

Technique: Converting data formats, Cleaning data, Extracting data
Tools: R
Data Format: Statistics