[R] Eval() or parse() do not work inside function

Duncan Murdoch murdoch.duncan at gmail.com
Tue Jul 27 21:13:10 CEST 2010


On 27/07/2010 2:34 PM, Jorge A. Ahumada wrote:
> I am writing a function where the arguments are names of objects or variable
> names in a data frame. To convert the strings to the objects I am using
> eval(parse(text=name)):
>
> f.graph.two.vbs<-function(dataname,v1){
>     
>      val<-paste(dataname,v1,sep="$")
>      val<-eval(parse(text=val))
>      val
>     }
>
> However running this returns an error:
>
> >f.graph.two.vbs("data","RECORD")
> Error in data$RECORD : $ operator is invalid for atomic vectors
>   

That is telling you that the object named data is not a list (or 
dataframe), it's an atomic vector.  When I create a dataframe named 
"data", and run your code, it's fine:  so I think this is simply a 
scoping error.  The value of your function is the same as if you had coded

data$RECORD

right in your function, and apparently the data object thus found was 
not a dataframe.


> Repeating the individual commands in the workspace does work though.. Do I
> need to pass the object data in the arguments for this to work?
>   

No, but you do need to make sure that the variable named by dataname is 
visible from within the function, or tell eval() to do the evaluation 
somewhere else.  I'd guess you want

  val<-eval(parse(text=val), envir=parent.frame())


Duncan Murdoch
> Thanks,
>
> Jorge
>



More information about the R-help mailing list