Andrew Little
Andrew Little

Reputation: 33

Why does the {magrittr}/{dplyr} pipe not work with certain functions (e.g. `mget`)?

I have seen this occur in a couple of instances but as it is an easy fix, I'd never asked:

library(dplyr)
iris_test_1 <- iris
iris_test_2 <- iris
iris_test_3 <- iris
iris_test_4 <- iris

# Find objects starting with certain letters in global
# environment (this relies on you having a clean global
# environment)

# Works
ge_datasets <- ls(pattern = "^iris_test_") 

mget(ge_datasets) %>% 
  bind_rows() %>% 
  as_tibble()

# Doesn't work
ls(pattern = "^iris_test_") %>% 
  mget() %>% 
  bind_rows() %>% 
  as_tibble()

# Works
ls(pattern = "^iris_test_") %>% 
  mget(.GlobalEnv) %>% 
  bind_rows() %>% 
  as_tibble()

Upvotes: 2

Views: 103

Answers (1)

akrun
akrun

Reputation: 887078

We can use parent.frame. By default, it uses as.environment(-1) i.e.

The default of -1 indicates the current environment of the call to get.

ls(pattern = "^iris_test_") %>%
      mget(envir = parent.frame())

The %>% creates an environment and as mget by default only checks in the current environment (as inherits = FALSE by default - it is TRUE in get though), it couldn't find the object. An option would be to specify inherits = TRUE

ls(pattern = "^iris_test_") %>%
   mget(inherits = TRUE)

Upvotes: 1

Related Questions