Possible duplicate:
How to write a function R that evaluates an expression in a data frame
I want to write a function that sorts data.frame - instead of using bulky order (). Given something like
> x=data.frame(a=c(5,6,7),b=c(3,5,1)) > x ab 1 5 3 2 6 5 3 7 1
I want to say something like:
sort.df(x,b)
So here is my function:
sort.df <- function(df, ...) { with(df, df[order(...),]) }
I was really proud of it. Given R's lazy rating, I realized that the parameter ... would only be evaluated when necessary, and by then it would be in scope because of the "c".
If I run the string βcβ directly, it works. But the function does not work.
> with(x,x[order(b),]) ab 3 7 1 1 5 3 2 6 5 > sort.df(x,b) Error in order(...) : object 'b' not found
What is wrong and how to fix it? For example, I often see such βmagicβ in packages like plyr. What a trick?
r ellipsis lazy-evaluation
dk.
source share