[R] "evaluating expressions" contained in a dataframe
Rui Barradas
ruipbarradas at sapo.pt
Tue Jul 3 21:24:30 CEST 2012
Hello,
I've changed the way you create data.frame 'tests', like it was the
conditions were factors, which are coded as integers. We need them of
class character to be parsed. Note that the same could be done with the
data.frame 'info' but it's not absolutely needed.
tests <- data.frame(rule=c("info$country == 'Greenland'", "info$age > 50"),
stringsAsFactors=FALSE)
str(tests)
tests
#------------------ This does the trick
fun <- function(x){
f <- function(){} # an empty function, no body
force(x) # evaluate the argument
body(f) <- parse(text=x) # parse it and assign the function
f # return the function
}
# See if it works
expr1 <- fun(tests$rule[1]) # This creates a function
expr1()
Hope this helps,
Rui Barradas
Em 03-07-2012 17:24, New RUser escreveu:
> #I have a dataframe called "tests" that contain "character expressions". These
> characters are rules that use data from within another dataframe. Is there
> any way within R I can access the rules in the dataframe called tests, and
> then "evaluate" these "rules"?
>
>
>
> #An example may better explain what I am trying to accomplish:
>
>
>
> tests <- data.frame(matrix(data=c("info$country == 'Greenland'", "info$age
>> 50"), nrow=2, ncol=1))
>
> names(tests) <- "rule"
>
>
>
> info <- data.frame(matrix(data=NA, nrow=5, ncol=3))
>
> names(info) <- c("first", "country", "age")
>
> info$name <- c("Mary", "Paul", "Robert", "John", "Ivan")
>
> info$country <- c("GReenland", "Iceland", "Ireland", "Greenland",
> "Greenland")
>
> info$age <- c(30, 55, 66, 79, 80)
>
>
>
> #e.g. for
>
> "info$country == 'Greenland'"
>
>
>
> #I want:
>
> info$country == 'Greenland'
>
> [1] FALSE FALSE FALSE TRUE TRUE
>
> #e.g.
> info$country == 'Greenland'
>
> info$age > 50
>
>
>
> #I tried this, but it does not "work":
>
> eval(tests$rule[1])
>
> [[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.
>
More information about the R-help
mailing list