Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pipe in magrittr package is not working for function rm()

Tags:

r

dplyr

magrittr

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()

like image 258
Ashrith Reddy Avatar asked Apr 04 '18 03:04

Ashrith Reddy


1 Answers

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

like image 68
akrun Avatar answered Nov 15 '22 01:11

akrun