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.
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.