[R] passing variable names to dplyr - SOLVED

Bos, Roger roger.bos at rothschild.com
Tue Jan 28 22:13:36 CET 2014


All,

I asked over at the manipulatr group and Hadley showed me how to do it.  In case anyone is interested I will post the solution here:

target <- "hp"
call <- substitute(mutate(mtcars, scale(target)), list(target = as.name(target)))
eval(call)

Thanks,

Roger

-----Original Message-----
From: arun [mailto:smartpink111 at yahoo.com]
Sent: Monday, January 27, 2014 5:25 PM
To: Bos, Roger
Subject: Re: [R] passing variable names to dplyr

Hi Roger,

This works on library(plyr), but not in dplyr.

target <- "hp"
res2 <- plyr:::mutate(mtcars,hp1= eval(parse(text= sprintf("scale(as.numeric(%s))",target))))
A.K.




On Monday, January 27, 2014 10:47 AM, "Bos, Roger" <roger.bos at rothschild.com> wrote:
All,

I would like to figure out how to pass variable names to the dplyr function mutate.  For example, this works because hp is one of the variable names on mtcars:

mutate(mtcars, scale(hp))

Let's says I want to pass in the target variable instead of hard-coding the name, as follows:

target <- "hp"
mutate(mtcars, scale(target))

That dones't work.  I read somewhere about using lapply, but that suggestion didn't work for me either:

target <- lapply("hp", as.symbol)
mutate(mtcars, scale(target))

Does anyone know how to do this?

Thanks,

Roger

***************************************************************
This message is for the named person's use only. It may contain confidential, proprietary or legally privileged information. No right to confidential or privileged treatment of this message is waived or lost by an error in transmission.
If you have received this message in error, please immediately notify the the sender by e-mail, delete the message and all copies from your system and destroy any hard copies.  You must not, directly or indirectly, use, disclose, distribute, print or copy any part of this message if you are not the intended recipient.
______________________________________________
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