[R] Passing in Condtions into Object

Daniel Malter daniel at umd.edu
Fri Sep 9 06:19:31 CEST 2011


Would:

tapply(mpg,list(year,manufacturer), function(x) length(unique(x)))

do what you are trying to accomplish? Or do you need very specific subsets?
If so, you can do:

year<-c(rep(1980,4),rep(1981,4))
manufacturer<-rep(c('A','B'),4)
mpg<-sample(c(1:2),8,replace=T)

guc<-function(x,y,z){length(unique(x[year==y&manufacturer==z]))}

#apply the function: e.g.

guc(mpg,1980,'A')

HTH,
Daniel


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')
> 
> Thank for any help in advance,
> 
> -- Adam
> 
> ______________________________________________
> 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.
> 

--
View this message in context: http://r.789695.n4.nabble.com/Passing-in-Condtions-into-Object-tp3800683p3800779.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list