[R] save conditions in a list
Rui Barradas
ruipbarradas at sapo.pt
Mon Jul 2 20:44:29 CEST 2012
Hello,
I'm not sure if this is what you want.
#-------------- Make up a dataset
set.seed(1)
n <- 1e2
DF <- data.frame(year=2010 + sample(3, n, TRUE),
day=sample(365, n, TRUE),
val=sample(100, n, TRUE))
a = "day > 100"; b = "val < 50"; c = "year == 2012"
conds <- list(a=a, b=b, c=c)
#-------------- This does it
fun <- function(condition, x){
f <- function(){}
if(class(x) == "matrix") x <- data.frame(x)
if(class(x) == "data.frame")
body(f) <- with(x, parse(text=condition))
else
body(f) <- parse(text=condition)
f()
}
#-------------- Test the function
year <- DF$year # See if it works with vectors
fun(b, year) # Must throw error
fun(c, year) # Should work
# And now with data.frames
result <- lapply(conds, fun, DF)
Reduce(`&`, result) # combine the results
Reduce(`|`, result) #
Hope this helps,
Rui Barradas
Em 02-07-2012 18:04, Christof Kluß escreveu:
> Hi
>
> how would you save conditions like
>
> a = "day > 100"; b = "val < 50"; c = "year == 2012"
>
> in a list? I like to have variables like "day", "val", "year" and a list
> of conditions list(a,b,c). Then I want to check if a & b & c is true or
> if a | b | c is true or similar things.
>
> Greetings
> Christof
>
> ______________________________________________
> 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.
>
More information about the R-help
mailing list