On Sep 8, 2011, at 8:21 PM, Adam Pridgen wrote:

Hello,

I am trying to pass a conditional expression into an expression to be
evaluated when ever an R statement is called.  For example:

get_unique_count <- function(df, select, field){
  uniqs <- unique(subset(df, select)[field])
  return (nrow(uniqs))
}


In this case select is a conditional statement year == 1980, and the
function would be called in the following manner:

library(ggplot2)
get_unique_count(mpg, year==1980, 'manufacturer')

Borrowing heavily from subset.data.frame:

get.uniq <- function (x, logic.expr, field)
{
    e <- substitute(logic.expr)
    r <- eval(e, x, parent.frame())
        if (!is.logical(r))
            stop("'subset' must evaluate to logical")
        r <- r & !is.na(r)
    if (missing(field))
        vars <- TRUE
    else {
        nl <- as.list(seq_along(x))
        names(nl) <- names(x)
        vars <- eval(substitute(field), nl, parent.frame())
    }
    uniqs <- unique(x[r, field, drop = FALSE])
   NROW(uniqs)
}

Thank for any help in advance,

-- Adam

______________________________________________
R-help@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.

David Winsemius, MD
Heritage Laboratories
West Hartford, CT

______________________________________________
R-help@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.

Reply via email to