[R] Using vectors of names in calls for functions

hadley wickham h.wickham at gmail.com
Thu Mar 5 23:13:34 CET 2009


Hi Pascal,

You need the aes_string function:

V1_P2_plot<-function(df, x, y, z) {
   ggplot(df, aes_string(x = x, y= y, fill = z)) +
    geom_tile()
}
j<-c("k", "l")
i<-"m"
m<-rnorm(25)
vsim<-cbind(expand.grid(k=1:5, l=1:5*10), m)

V1_P2_plot(df=vsim, x=j[1], y=j[2], z=i)

Hadley

On Thu, Mar 5, 2009 at 3:16 PM, Pascal Boisson <hoothootprod at gmail.com> wrote:
> Dear R people,
>
> it is a pleasure to try and use functionnalities that are in ggplot,
> even with my poor capacities in R. so far, i'dlike to be able to use
> these in my own function, and to
>
> "be able to use it repeatedly from
> vectors where I store the names of my columns."
>
> I have understood that this is a very discussed topic, that many post
> have been exhanged but I cannot understand what is the good way to
> handle this and not to use this vectors of names ...
>
> below is the idea of what I would like to have:
>
>            V1_P2_plot<-function(df, x, y, z) {
>                pp<-ggplot(df, aes(x = x, y= y , z = z ))
>                pp<-pp + geom_tile(aes(fill= z))
>                return(pp)
>            }
>
> that would allow this type of call :
> j<-c("k", "l")
> i<-"m"
> m<-rnorm(25)
> vsim<-cbind(expand.grid(k=1:5, l=1:5*10), m)
>
> V1_P2_plot(df=vsim, x=j[1], y=j[2], z=i)
>
> This is obviously not working, and I understand from the numerous discussion on
> the R help list that this is related to references and calls.
> I spend the whole afternoon on these topics and it did not allowed
> me to understand the major principles. And most of my trials with
> deparse(substitute()) and eval(parse()) where inefficient.
>
>
> I was only able to have the following functionning :
>
> qplot(get(j[1]),get(i),data=vsim, geom=c("line", "point"),
> group=get(j[2]), colour=get(j[2]), xlab=j[1],ylab=i )
>
> but this strategy fails as soon as I want to call it from my function.
> and I also understood that the "get()" way and the vector of names are
> not the good way to adress this.
> but I was not able to use/generalise the examples so far discussed on
> this list :
>
> mytable <- function(x,y) eval.parent(substitute(table(x,y)))
>
> logplot <- function(y, ylab = deparse(substitute(y))) {
>                 ylab
>                 y <- log(y)
>                 plot(y, ylab = ylab)
>                 }
>
> to achieve my problem.
>
> but i I would be very happy if you could help me on this.
>
> Best regards
>
> Pascal Boisson
>
> ______________________________________________
> 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.
>



-- 
http://had.co.nz/




More information about the R-help mailing list