Skip to content

across(all_of()) doesn't see variables outside it's own environment #5498

Description

@vovoch

I faced the strange behavior in mutate(across(all_of())) combination of functions. Objects defined previously cannot be used inside of this construction. Two examples:

reduce(mget(ls(pattern = "^mcmc_stat_")), full_join, by = "ParameterMCMC") %>%
    select(ParameterMCMC, Median, LCL95, HCL95, Mean, SD) %>%
    nest(data = !all_of("ParameterMCMC")) %>%
    mutate(retaining_cols = map(ParameterMCMC, ~global_settings$mcmc_param_presets %>%
                                  filter(INPUT == .x) %>% pull(COLUMNS) %>% unlist()),
           data = map2(retaining_cols, data, ~.y %>% mutate(across(!all_of(.x), ~NA))))

#Error: object '.x' is not found
reduce(mget(ls(pattern = "^mcmc_stat_")), full_join, by = "ParameterMCMC") %>%
    select(ParameterMCMC, Median, LCL95, HCL95, Mean, SD) %>%
    nest(data = !all_of("ParameterMCMC")) %>%
    mutate(data = map2(ParameterMCMC, data, ~{
      retaining_cols <- global_settings$mcmc_param_presets %>%
        filter(INPUT == .x) %>% pull(COLUMNS) %>% unlist()
      .y %>% mutate(across(!all_of(retaining_cols), ~NA))
    }))

#Error: object 'retaining_cols' is not found

But objects from the R_GlobalEnv can be used. For example, the "<<-" operator in the following code resolves this problem and works in the expected way:

reduce(mget(ls(pattern = "^mcmc_stat_")), full_join, by = "ParameterMCMC") %>%
    select(ParameterMCMC, Median, LCL95, HCL95, Mean, SD) %>%
    nest(data = !all_of("ParameterMCMC")) %>%
    mutate(data = map2(ParameterMCMC, data, ~{
      retaining_cols <<- global_settings$mcmc_param_presets %>%
        filter(INPUT == .x) %>% pull(COLUMNS) %>% unlist()
      .y %>% mutate(across(!all_of(retaining_cols), ~NA))
    }))

Metadata

Metadata

Assignees

Labels

reprexneeds a minimal reproducible example

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions