Joseph Boyer
2012-Jun-22 21:09 UTC
[R] dropping variables from a data frame inside a function
Why doesn't this work? #Drop a variable name from a data frame DropLikeSAS <- function(x,df) { df[[x]] <- NULL 0 } DropLikeSAS("VarName", DataFrameName) Try it. The column VarName will not be deleted from the data frame DataFrameName. But x <- "VarName" DataFrameName[[x]] <- NULL Works. [[alternative HTML version deleted]]
David Winsemius
2012-Jun-22 21:19 UTC
[R] dropping variables from a data frame inside a function
On Jun 22, 2012, at 5:09 PM, Joseph Boyer wrote:> Why doesn't this work? > > #Drop a variable name from a data frame > > DropLikeSAS <- function(x,df) { > > df[[x]] <- NULL > > 0 > > } > > DropLikeSAS("VarName", DataFrameName) > > > Try it. The column VarName will not be deleted from the data frame > DataFrameName. > > > But > > x <- "VarName" > DataFrameName[[x]] <- NULL > > Works. > > > > [[alternative HTML version deleted]] > > ______________________________________________ > R-help at r-project.org mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide http://www.R-project.org/posting-guide.html > and provide commented, minimal, self-contained, reproducible code.David Winsemius, MD West Hartford, CT
David Winsemius
2012-Jun-22 21:22 UTC
[R] dropping variables from a data frame inside a function
On Jun 22, 2012, at 5:09 PM, Joseph Boyer wrote:> DropLikeSAS <- function(x,df) { > > df[[x]] <- NULL > > 0 > > } > > DropLikeSAS("VarName", DataFrameName)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
Duncan Murdoch
2012-Jun-22 22:58 UTC
[R] dropping variables from a data frame inside a function
On 12-06-22 5:09 PM, Joseph Boyer wrote:> Why doesn't this work?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> > #Drop a variable name from a data frame > > DropLikeSAS<- function(x,df) { > > df[[x]]<- NULL > > 0 > > } > > DropLikeSAS("VarName", DataFrameName) > > > Try it. The column VarName will not be deleted from the data frame DataFrameName. > > > But > > x<- "VarName" > DataFrameName[[x]]<- NULL > > Works. > > > > [[alternative HTML version deleted]] > > ______________________________________________ > R-help at r-project.org mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide http://www.R-project.org/posting-guide.html > and provide commented, minimal, self-contained, reproducible code.