[R] passing function parameters into a 'with' statement to dynamically pick out columns

Jeff Newmiller jdnewmil at dcn.davis.CA.us
Wed Jun 20 17:49:26 CEST 2012


"With" is designed for interactive use, so you are right that it is not the answer.

You can use list indexing with column names within functions, though, like df[[scaling.column]] or df[["all"]].
---------------------------------------------------------------------------
Jeff Newmiller                        The     .....       .....  Go Live...
DCN:<jdnewmil at dcn.davis.ca.us>        Basics: ##.#.       ##.#.  Live Go...
                                      Live:   OO#.. Dead: OO#..  Playing
Research Engineer (Solar/Batteries            O.O#.       #.O#.  with
/Software/Embedded Controllers)               .OO#.       .OO#.  rocks...1k
--------------------------------------------------------------------------- 
Sent from my phone. Please excuse my brevity.

David Marx <dmarx at SOUNDEXCHANGE.COM> wrote:

>Hi,
>
>I've built a function to generate plots and would like to be able pass
>in column names as a parameter. Here's a boiled down version of what I
>have right now:
>
>pmts <- data.frame(date=c(1,2,3),
>all=c(5,6,7),maj=c(4,5,6),ind=c(3,4,5))
>perc.mktshare <- function(df){  
>  range1 <- floor(min(with(df, 100*ind/all)))
>  range2 <- ceiling(max(with(df, 100*ind/all)))  
>with(df,plot(date,100*ind/all,ylim=c(range1,range2),ylab="%
>Marketshare"))
>}
>perc.mktshare(pmts)
>
>What I'd like to do is something like this:
>
>perc.mktshare <- function(df, scaling.column){  
>  range1 <- floor(min(with(df, 100*scaling.column/all)))
>  range2 <- ceiling(max(with(df, 100*scaling.column/all)))  
>with(df,plot(date,100*"scaling.column"/all,ylim=c(range1,range2),ylab="%
>Marketshare"))
>}
>perc.mktshare(pmts,"ind")
>perc.mktshare(pmts,"maj")
>
>I've tried going about this a couple of different ways but I can't make
>it work. My suspicion is that there's probably no way to do this using
>the 'with' statement and I'll have to trim the input dataframe to the
>pertinent columns first using subset or something.
>
>Thanks for your help!
>
>David
>
>______________________________________________
>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