1

I have a data set with many columns from multiple sources, and I would like to unite each set of columns into a single column per set using mutate_at in dplyr, based on the condition in another column. Here's an example of what I want, using hardcoded column names and dplyr::mutate:

library (dplyr)
library (tibble)
library (magrittr)

data <- tribble(
  ~source,    ~stars_1  ,  ~stars_2 ,  ~dashes_1  ,  ~dashes_2  , 
  "1"    ,    "*"       ,  "-"      ,  "-"        ,  "#"        , 
  "2"    ,    "+"       ,  "*"      ,  "+"        ,  "-"        , 
  "2"    ,    "+"       ,  "*"      ,  "+"        ,  "-"        
)      

dataClean <- data %>% 
  mutate (stars_1 = ifelse (source == 1, stars_1, stars_2),
          dashes_1 = ifelse (source == 1, dashes_1, dashes_2)) %>% 
  mutate (stars_Check = stars_1 == "*",
          dashes_Check = dashes_1 == "-")

I'm attempting to do this programatically, but it's not providing the desired result.

baseColNames <- c("stars", "dashes")

data %>% 
  mutate_at (.cols = paste0(baseColNames, "_1"), 
             .funs = funs(ifelse (source == 1, paste0(., "_1"), paste0(., "_2"))))

I'd prefer to do this in dplyr and mutate_at for ease of understanding by others. Also, the data set is very large, so I would prefer not to gather and spread and/or use an lapply, which from prior experience would likely achieve the goal but at the expense of runtime.

Appreciate the help.


Update: Refer to this post. Asks the same question.

Lal J
  • 11
  • 2
  • 1
    Check this [SO post](https://stackoverflow.com/questions/62556564/refer-to-column-names-dynamically-inside-mutate-statements-dplyr) where a similar issue is discussed. All the answerers suggest that it might not be possible to use the scoped variants of `mutate`, but a `tidyr` approach is suggested. `gather` and `spread` will be replaced by the new, more efficient `pivot_longer` and `pivot_wider`. Would they be ok as an answer? – Ric S Jun 25 '20 at 07:07
  • Thanks @RicS that post is asking the same question. I will refer to that one for how to deal with this issue and try the new versions of the `pivot_` functions. – Lal J Jun 26 '20 at 14:13

0 Answers0