How to write an R function that evaluates an expression within a data-frame
Posted
by
Prasad Chalasani
on Stack Overflow
See other posts from Stack Overflow
or by Prasad Chalasani
Published on 2011-01-13T16:50:46Z
Indexed on
2011/01/13
16:53 UTC
Read the original article
Hit count: 211
Puzzle for the R cognoscenti: Say we have a data-frame:
df <- data.frame( a = 1:5, b = 1:5 )
I know we can do things like
with(df, a)
to get a vector of results.
But how do I write a function that takes an expression (such as a
or a > 3
) and does the same thing inside. I.e. I want to write a function fn
that takes a data-frame and an expression as arguments and returns the result of evaluating the expression "within" the data-frame as an environment.
Never mind that this sounds contrived (I could just use with
as above), but this is just a simplified version of a more complex function I am writing. I tried several variants ( using eval
, with
, envir
, substitute
, local
, etc) but none of them work. For example if I define fn
like so:
fn <- function(dat, expr) {
eval(expr, envir = dat)
}
I get this error:
> fn( df, a )
Error in eval(expr, envir = dat) : object 'a' not found
Clearly I am missing something subtle about environments and evaluation. Is there a way to define such a function?
© Stack Overflow or respective owner