R‎ > ‎R‎ > ‎

Functions, Objects and Dataframes

posted Mar 24, 2014, 7:16 AM by David Eagle
When working with data frames in R, there can be some unexpected behavior when calling functions. It is not always clear if/what data frame R will reference when using a function. Also, it would be nice to write functions that do not need to be referenced with a specific data frame, but have one passed to them. 

Enter the command match.call(), a function that according to the ever-so-helpful R help "returns a call in which all of the specified arguments are specified by their full names." Well, whatever the case, this function can be used to attach an object/dataframe that to call another function.

For example (thanks stack overflow!):

#Makes a generic function attach to a specific data frame to another function




#create generic function:

fn <- function(dat, expr) {

  mf <- match.call() # makes expr an expression that can be evaluated

  eval(mf$expr, envir = dat)


#see it in action

P <- function(x) x+1

fn(d,P(x)) #returns 11

P(x) #returns 3