[R] How to translate string to variable inside a command in an easy way in R
djnordlund at frontier.com
Wed Jul 13 19:30:13 CEST 2011
> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org]
> On Behalf Of UriB
> Sent: Wednesday, July 13, 2011 9:28 AM
> To: r-help at r-project.org
> Subject: Re: [R] How to translate string to variable inside a command in
> an easy way in R
> Here is another question
> I want to have a function that get a string for example
> y="AMI" and make commands like the following
> agg<-aggregate(numAMI ~MemberID,right.a,sum)
> Note that I know that numAMI is part of right.a because another function
> with the string AMI already generated it.
> Is there a way to do it without paste parse and eval?
> I can do it by the following commands for y="AMI"
> text2<-"~MemberID, right.a, sum)"
> If you can have a shorter code for it then it can be productive.
Well, you could do the above in one line (sorry, my email client is breaking the line)
>agg <- eval(parse(text=paste("aggregate(num",y,"~MemberID,right.a,sum)",sep='')))
You can put that in a function and call it like
>your_function <- function(y) eval(parse(text=paste("aggregate(num",y,"~MemberID,right.a,sum)",sep='')))
>agg <- your_function(y='AMI')
However, you seem to be trying to wrestle R to the ground to get it to do things your way. Maybe if you gave R-help some context about your overall task (including why you need to construct these commands), someone could provide suggestions on solving your programming tasks in a more R-ish way. Just a thought.
Bothell, WA USA
More information about the R-help