I have a data frame with 40 variables G1_a, G1_b, ... till G20_a, G20_b (stemming from a survey). I want to create 20 new variables G1 ... G20 that summarize the existing variables.
data <- data.frame(G1_a = c(0, 0, 0, 1, NA),
G1_b = c(0, 0, 1, 1, NA),
G2_a = c(0, 0, 0, 1, NA),
G2_b = c(0, 0, 1, 1, NA))
# Reshaping without for-loop:
data <- data %>%
mutate(G1 = case_when(
G1_a == 1 ~ "own_offer",
G1_b == 1 ~ "no_offer",
T ~ NA_character_
))
data <- data %>%
mutate(G2 = case_when(
G2_a == 1 ~ "own_offer",
G2_b == 1 ~ "no_offer",
T ~ NA_character_
))
I want to automate the creation of the new variables in a for-loop, something like:
# Reshaping with for-loop:
for(i in 1:2) {
data <- data %>%
mutate(assign(paste0("G", i), case_when(
get(paste0("G", i, "_a")) == 1 ~ "own_offer",
get(paste0("G", i, "_b")) == 1 ~ "no_offer",
T ~ NA_character_
)))
}
My question includes two parts:
1) Is it possible to combine assign with mutate? I'm aware of approaches like mutate(df, !!varname := Petal.width * n) (see here) to dynamically assign parameter names. However, I was unable to combine it with the data reshaping I want to run.
2) Does dplyr allow the use of paste0 together with case_when and mutate?
G1_a,G1_betc. were provided as dummies, but should be encoded as categorical variables. EveryG1_aandG1_bshould becomeG1,G2_aandG2_bbecomesG2etc.