[R] how can I evaluate a formula passed as a string?

From: Mike Williamson <this.is.mvw_at_gmail.com>
Date: Thu, 24 Jun 2010 10:16:29 -0700


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

--
Help protect Wikipedia. Donate now:
http://wikimediafoundation.org/wiki/Support_Wikipedia/en

	[[alternative HTML version deleted]]

______________________________________________
R-help_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
Received on Thu 24 Jun 2010 - 17:18:59 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Thu 24 Jun 2010 - 17:40:36 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive