6
x = 10
rm(x) # removed x from the environment

x = 10
x %>% rm() # Doesn't remove the variable x 

1) Why doesn't pipe technique remove the variable?
2) How do I alternatively use pipe and rm() to remove a variable?

Footnote: This question is perhaps similar to Pipe in magrittr package is not working for function load()

oguz ismail
  • 1
  • 16
  • 47
  • 69
Ashrith Reddy
  • 1,022
  • 1
  • 13
  • 26
  • Like all the operations in `dplyr` you need to assign the value back to the original variable if you want to see it's effect. Do `x <- x %>% rm()` and then print `x`. – Ronak Shah Apr 04 '18 at 04:06
  • Kind of like doing `function(x) {rm(x)}` although I don't think that explains why the dlpyr-assigning the value back to the object succeeds. – IRTFM Apr 04 '18 at 04:21
  • `rm` requires the variable name in some fashion, but the way pipelines are evaluated, `x` is already retrieved by the time it gets passed to `rm`, so the name is not available on the right-hand side of the pipe. The value is stored as a temporary variable, but the original name is discarded after it's used. Thus, the only way to pipe into `rm` is to quote the variable name in some fashion, and the quoting has to be in the same call as the variable, e.g. `x <- 10; quote(x) %>% purrr::invoke(rm, ., .env = .GlobalEnv)` – alistaire Apr 05 '18 at 02:21

1 Answers1

7

Use the %<>% operator for assigning the value to NULL

x %<>% 
   rm()

In the pipe, we are getting the value instead of the object. So, by using the %<>% i.e. in place compound assignment operator, the value of 'x' is assigned to NULL

x
#NULL

If we need the object to be removed, pass it as character string, feed it to the list argument of rm which takes a character object and then specify the environment

x <- 10
"x" %>% 
    rm(list = ., envir = .GlobalEnv)

When we call 'x'

x

Error: object 'x' not found

The reason why the ... doesn't work is that the object . is not evaluated within the rm

x <- 10
"x" %>%
    rm(envir = .GlobalEnv)

Warning message: In rm(., envir = .GlobalEnv) : object '.' not found


Another option is using do.call

x <- 10
"x" %>%
   list(., envir = .GlobalEnv) %>% 
   do.call(rm, .)
x

Error: object 'x' not found

akrun
  • 874,273
  • 37
  • 540
  • 662