Skip to content

dropping variables from a data frame inside a function

5 messages · Joseph Boyer, David Winsemius, R. Michael Weylandt +1 more

#
On Jun 22, 2012, at 5:09 PM, Joseph Boyer wrote:

            
David Winsemius, MD
West Hartford, CT
#
On Jun 22, 2012, at 5:09 PM, Joseph Boyer wrote:

            
Sorry for the blank message>

 > DropLikeSAS <- function(x,df) {
+                                df[[x]] <- NULL
+                               return(df) }
 >
 > DropLikeSAS("b", df)
     a
1   1
2   2
3   3
4   4
5   5
6   6
7   7
8   8
9   9
10 10
 >


David Winsemius, MD
West Hartford, CT
#
I think the OP might also be tripped up on the fact that R is
pass-by-value so effects on df inside DropLikeSAS won't have impact
outside the function's scope. The df inside of DropLikeSAS() is
changed as expected, but that has no effect on the df outside that
function.

To the OP: There are ways to get pass-by-reference behavior (which I
think is what you are expecting), but the default is pass-by-value for
good reason. Give it a shot for a while and see if you come to like it
-- I think you will.

Best,
Michael
On Fri, Jun 22, 2012 at 4:22 PM, David Winsemius <dwinsemius at comcast.net> wrote:
#
On 12-06-22 5:09 PM, Joseph Boyer wrote:
David gave you a solution that works.  The answer to this question is 
that unlike SAS, R is a computing language that has an idea of variable 
scoping:  when you modify the argument df in DropLikeSAS, you are making 
local changes, not global ones.

Duncan Murdoch