Hi,
I have this df:
source <- data.frame(
stringsAsFactors = FALSE,
URN = c("21GB0420348376",
"21GB040308396","21GB042478907","21GB0418448382","21GB7680334731",
"21GB04110294317","21GB0424590378906",
"21GB04123238885","21GB0424550377080",
"21GB0418447308379","21GB0415210263918","21GB04550377079",
"21GB0414370263920","21418452110311403",
"21GB0423572366131"),
QF0 = c(2, 6, 33, 35, 32, 4, 33, 1, 32, 64, 2, 64, 2, 8, 33),
Gender = c(2, 1, 2, 2, 2, 1, 2, 1, 2, 1, 2, 1, 2, 2, 1)
)
Thank to you guys I managed to do this to recode QF0 to individual variables based on a binary code:
library(tidyverse)
tf <- c(TRUE,FALSE)
combs <- expand.grid(map(1:7,~tf))
(c2 <- sweep(combs,MARGIN=2,2^(0:6),`*`))
c2$rsum <- rowSums(c2)
head(c2)
result <- source %>% left_join(c2,by=c("QF0"="rsum")) %>%
mutate(across(.cols=c(-URN,-QF0),~as.integer(.>0)))
result
Now, I am wondering if I can create these output variables with a name given (instead of Var1, Var2 etc) two ways:
- The same as recoded variable so: QF01, QF02, QF03...QF07
- Defined name (for example "Choice"): Choice1, Choice2, Choice3 ...Choice7
Can you help?