[R] Passing the name of a variable to a function

Anthony Staines anthony.staines at gmail.com
Wed Aug 4 15:56:58 CEST 2010


Dear colleagues,

I have a problem which has bitten me occasionally. I often need to
prepare graphs for many variables in a data set, but seldom for all.
or for any large number of sequential or sequentially named variables.
Often I need several graphs for different subsets of the dataset
for a given variable.  I run into similar problems with other needs
besides graphing.

 What I would like to do is something like "write a function which
takes the *name* of a variable, presumably a s a character string,
from a dataframe, as one argument, and the dataframe, as a second argument".

For example, where y is to be the the name of a variable in a given
dataframe d, and the other variables needed, T, M and so on, are
to be found in the same dataframe :-

pf <- function (y,data,...) {
p1 <- xyplot(y~x|T,data)
p2 <- xyplot(y~x|T,subset(data,M == 2))
p3 <- xyplot(y~x|T,subset(data,M == 4))
#print(p1,p2,p3....)
}
 pf(Score1,data)
pf(Score2,data)


This fails, because, of course, Score 1, Score 2 etc.. are  not
defined, or if you pass them as pf(data$Score2,data), then when you
subset the
data, data$Score2 is now the wrong shape.  I've come up with various
inelegant hacks, (often with for loops), for getting around this over
the
last few years, but I can't help feeling that I'm missing something
obvious, which I've been too dim to spot.

Please note the answer to my requirements is *not* a clever use of
lattice. This question goes beyond graphs.
All suggestions gratefully received!

Best wishes,
Anthony Staines
-- 
Anthony Staines,  Professor of Health Systems Research,
School  of Nursing, Dublin City University, Dublin 9, Ireland.
Tel:- +353 1 7007807. Mobile:- +353 86 606 9713



More information about the R-help mailing list