[R] "evaluating expressions" contained in a dataframe

arun smartpink111 at yahoo.com
Thu Jul 5 06:01:33 CEST 2012



Hello,

Your "eval(tests$rule[1])" needs a slight modification to get the results.



Try this:
tests<-read.table(text="
 rule
 info$country=='Greenland'
 info$age>50
 ",sep="",header=TRUE,stringsAsFactors=FALSE)


info<-data.frame(first=rep(NA,5),country=c("GReenland","Iceland","Ireland","Greenland","Greenland") ,age=c(30,55,66,79,80),name=c("Mary","Paul","Robert","John","Ivan"))
#1st condition

eval(parse(text=tests$rule[1]))
[1] FALSE FALSE FALSE  TRUE  TRUE

#2nd condition

eval(parse(text=tests$rule[2]))
[1] FALSE  TRUE  TRUE  TRUE  TRUE

# tests[1,1] condition: subset info
info[eval(parse(text=tests$rule[1])),]
  first   country age name
4    NA Greenland  79 John
5    NA Greenland  80 Ivan

#tests[2,1] condition: subset info
info[eval(parse(text=tests$rule[2])),]
  first   country age   name
2    NA   Iceland  55   Paul
3    NA   Ireland  66 Robert
4    NA Greenland  79   John
5    NA Greenland  80   Ivan

A.K.





----- Original Message -----
From: New RUser <newruser2012 at gmail.com>
To: r-help at r-project.org
Cc: 
Sent: Tuesday, July 3, 2012 12:24 PM
Subject: [R] "evaluating expressions" contained in a dataframe

#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