Renaming new variables after conversion

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:

  1. The same as recoded variable so: QF01, QF02, QF03...QF07
  2. Defined name (for example "Choice"): Choice1, Choice2, Choice3 ...Choice7

Can you help?

This is a good use for dplyr::rename_with. I would do something like this, and change new_col_name_base as needed.

new_col_name_base <- 'Choice' # Or this can be 'QF0'
result %>% 
    dplyr::rename_with(
        .fn = function(nm) {
            # A function where each column name is the argument nm
            stringr::str_replace_all(string = nm, pattern = 'Var', replacement = new_col_name_base) # Change 'Choice' as needed
        }
    )

Created on 2022-03-28 by the reprex package (v1.0.0)

Hopefully that helps

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.