Mike Williamson
2010-Jun-24 17:16 UTC
[R] how can I evaluate a formula passed as a string?
Hey everyone, I've been using 'R' long enough that I should have some idea of what the heck either expression() or eval() are really ever useful for. I come across another instance where I WISH they would be useful, but I cannot get them to work. Here is the crux of what I would like to do: presume df looks like this A B C === === ==M 45 0 M 46 1 F 42 0 F 42 1 M 46 1 and I want to make it look like this, using the function below (allowing for other options besides "count" or "median"): A B Count of C Median of C === === ========== ===========M 45 1 0 M 46 2 1 F 42 2 0.5 blah <- function(df=df, dup="C", aligns=c("A","B"), dupFuns=c("length(unique(x)","median(x)", dupNames) { ### A function where it will "widen" the df based upon the "aligns" columns, taking care to summarize the "dup" column using the "dupFuns" tmp <- aggregate(df[,dup], by=as.list(df[,aligns]), FUN=function(x) { * eval(dupFuns[1])* } ) names(tmp)[length(names(tmp)] <- dupNames[1] for (i in c(2:length(dupFuns))) { tmp <- merge(tmp, aggregate(df[,dup], by=as.list(df[,aligns]), FUN=function(x) { *eval(dupFuns[i])* } ), all = TRUE) names(tmp)[length(names(tmp)] <- dupNames[i] } } Everything in it works OK, except that the "eval" function doesn't work as it should. How can I get, for instance, "length(unique(x))" (as a character string) to become length(unique(x)) (a function to be evaluated as shown above). Thanks! Mike "Telescopes and bathyscaphes and sonar probes of Scottish lakes, Tacoma Narrows bridge collapse explained with abstract phase-space maps, Some x-ray slides, a music score, Minard's Napoleanic war: The most exciting frontier is charting what's already here." -- xkcd -- Help protect Wikipedia. Donate now: http://wikimediafoundation.org/wiki/Support_Wikipedia/en [[alternative HTML version deleted]]
Peter Langfelder
2010-Jun-24 17:29 UTC
[R] how can I evaluate a formula passed as a string?
On Thu, Jun 24, 2010 at 10:16 AM, Mike Williamson <this.is.mvw at gmail.com> wrote:> Hey everyone, > > ? ?I've been using 'R' long enough that I should have some idea of what the > heck either ? expression() ?or eval() ?are really ever useful for. ?I come > across another instance where I WISH they would be useful, but I cannot get > them to work.Example: eval(parse(text = "3*3")) Peter
Seemingly Similar Threads
- ideas, modeling highly discrete time-series data
- anyone know why package "RandomForest" na.roughfix is so slow??
- question regarding "varImpPlot" results vs. model$importance data on package "RandomForest"
- How to get 'R' to talk BACK to other languages / scripts??
- how to convert "sloppy data" into a time series?