On Jun 20, 2012, at 16:45 , David Marx 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.
> 

Something with eval(bquote(.....)) should do it, e.g.

foo <- function(col) eval(bquote(with(airquality, plot(.(col), Ozone))))
foo(quote(Wind))
foo(quote(Solar.R))

Or, use .(as.name(col)) inside bquote, and foo("Wind") in the call.

Possibly, substitute() can be used as well, but it might get tricky.



> Thanks for your help!
> 
> David
> 
> ______________________________________________
> R-help@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.

-- 
Peter Dalgaard, Professor
Center for Statistics, Copenhagen Business School
Solbjerg Plads 3, 2000 Frederiksberg, Denmark
Phone: (+45)38153501
Email: pd....@cbs.dk  Priv: pda...@gmail.com

______________________________________________
R-help@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.

Reply via email to