Skip to content

recode_shadow() doesn't support applying to multiple columns via across() or similar methods, right? #348

@SchmidtPaul

Description

@SchmidtPaul

Problem Description

When working with multiple columns that need shadow recoding in naniar, there's currently no way to apply recode_shadow() to multiple columns at once using across() or similar methods. This requires verbose repetition of the recoding logic for each column.

Current Workaround

Currently, we need to chain multiple recode_shadow() calls, one for each column:

library(naniar)
library(tidyverse)

tbl <- tibble(var = c('A', 'B', 'C'), val1 = c('12', '*', 'x'), val2 = c('1', '2', 'x'))
cols <- c('val1', 'val2')


# adressing each one ------------------------------------------------------
tbl %>% 
  bind_shadow() %>%  
  recode_shadow(val1 = .where(val1 == '*' ~ '*', val1 == 'x' ~ 'x')) %>% 
  recode_shadow(val2 = .where(val2 == '*' ~ '*', val2 == 'x' ~ 'x'))
#> # A tibble: 3 × 6
#>   var   val1  val2  var_NA val1_NA val2_NA
#>   <chr> <chr> <chr> <fct>  <fct>   <fct>  
#> 1 A     12    1     !NA    !NA     !NA    
#> 2 B     *     2     !NA    NA_*    !NA    
#> 3 C     x     x     !NA    NA_x    NA_x

Created on 2024-12-16 with reprex v2.1.1

But I did attempt to create a helper function to use with reduce():

library(naniar)
library(tidyverse)

tbl <- tibble(var = c('A', 'B', 'C'), val1 = c('12', '*', 'x'), val2 = c('1', '2', 'x'))
cols <- c('val1', 'val2')

# trying something like across() ------------------------------------------
.custom_where <- function(colname) {
  list(condition = list(quo(!!sym(colname) == '*'), quo(!!sym(colname) == 'x')),
       suffix = list('*', 'x'))
}

tbl %>% 
  bind_shadow() %>%
  reduce(cols, ~ .x %>% recode_shadow(!!sym(.y) := .custom_where(.y)), .init = .)
#> # A tibble: 3 × 6
#>   var   val1  val2  var_NA val1_NA val2_NA
#>   <chr> <chr> <chr> <fct>  <fct>   <fct>  
#> 1 A     12    1     !NA    !NA     !NA    
#> 2 B     *     2     !NA    NA_*    !NA    
#> 3 C     x     x     !NA    NA_x    NA_x

Created on 2024-12-16 with reprex v2.1.1

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions