0

I would like to learn about how to handle an input of a variable name in a function. For example, I have written a function like this:

bin_multi <- function(y, dataframe, sel = NULL){
  if(!is.null(sel)) {
     dataframe <- dataframe[,sel]}
  else {
     dataframe <- dataframe[!y]}
}

Where dataframe is the input dataframe, y is the target variable in the dataframe, sel is the selection of columns from dataframe, for example, sel = c(1,2,3).

The purpose of this function is to simply take a subset of dataframe with a given sel, and when sel is not given, exclude y the target variable from the dataframe.

My question is, how could I refer properly to y in this function? In the input, y is the name of a variable. Could deparse() solve this problem?

Thank you all.

user95902
  • 149
  • 2
  • 3
  • 13
  • Enter y as a character vector and then use `grep` or `grepl`: `dataframe <- dataframe[!grepl(y, names(dataframe), fixed=TRUE)]`. – lmo Feb 21 '17 at 13:05
  • @lmo Thanks! But if not enter y as a character? Because this is only a small part of the full function and if y is entered as a character then it would get messier in the rest. – user95902 Feb 21 '17 at 13:17
  • 1
    It is unclear to me how it would get messier, but a simple solution would be to make a copy of y at the top of the function and use this throughout: `myY <- dataframe[, y]`. Then replace y with myY in your code. – lmo Feb 21 '17 at 13:25
  • @lmo Yeah that works too! – user95902 Feb 21 '17 at 13:41

1 Answers1

0

I think this will work:

bin_multi <- function(y, dataframe, sel = NULL){

  if(!is.null(sel)) {

     dataframe <- dataframe[,sel]

  } else {

     dataframe <- dataframe[,which(names(dataframe) != deparse(substitute(y)))]

  }

}

That's drawing on this answer to turn your object name into a string.

Community
  • 1
  • 1
ulfelder
  • 5,305
  • 1
  • 22
  • 40
  • Thanks! I had `deparse(substitute(y))` but I did not use `which(names(.))` not including `y`. This is exactly how I want it to work! – user95902 Feb 21 '17 at 13:40