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

David Marx dmarx at SOUNDEXCHANGE.COM
Wed Jun 20 16:45:37 CEST 2012


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



More information about the R-help mailing list