Reputation: 1693
i am trying to create a function in which i want to remove one of the variables passed to it.
now R works in annoying ways in that it copies the object instead of giving a reference. (technically the copying only happens if you make a change... but meh...)
a=function(b){
rm(b)
# rm(b)
}
test=123
a(test) # will remove b, not test
# you can verify that by adding the 2nd rm(b)
i tried
a=function(b){
rm(match.call()[[2]])
}
but that gives the error:
Error in rm(match.call()[[3]]) :
... must contain names or character strings
Upvotes: 2
Views: 2213
Reputation: 21502
similar to nrussell's answer, here's the line from cgwtools::askrm
which does an arbitrary function call on the selected object:
call(fn, as.name(thenam)), envir = parent.frame(1))
(and, yes, I'm plugging my own toolkit here :-) )
Upvotes: 0
Reputation: 18602
Try this:
Foo <- function(x){
Sx <- deparse(substitute(x))
rm(list=Sx,envir=sys.frame(-1))
}
##
Z <- 123
ls()
##
[1] "Foo" "Z"
##
Foo(x=Z)
ls()
[1] "Foo"
Upvotes: 3