[R] Passing variable names in quotes to a function

Uwe Ligges ligges at statistik.tu-dortmund.de
Wed Dec 2 07:45:47 CET 2015



On 02.12.2015 06:11, Brant Inman wrote:
> I am trying to build a function that can accept variables for a regression.  It would work something like this:
>
> ---
> # Y = my response variable (e.g. income)
> # X = my key predictor variable (e.g. education)
> # subY = a subsetting variable for Y (e.g. race)
> # subY.val = the value of the subsetting value that I want (e.g. ‘black’)
>
> foo <- function(Y, X, subY, subY.val, dataset){
>
>    if(is.na(subY) == F) {


Not sure why this all is needed, but you can insert here:

if(is.character(subY.val) || is.factor(subY.val)) subY.val <- 
shQuote(subY.val)

Best,
Uwe Ligges


>       Y <- paste(Y, ‘[‘, subY, ‘==‘, subY.val, ‘]’)
>    }
>    FORMULA <- paste(Y ~ X)
>    fit <- some.regression.tool(FORMULA, data=dataset)
>
>    return(some.data.after.processing)
> }
> ---
>
> If I call this function with, foo(income, education, race, “black”, my.dataset), I do not get the result that I need because the FORMULA is "income[race==black] ~ education” when what I need is “income[race==‘black’] ~ education”.  How do I get the quotes to stay on ‘black’?  Or, is there a better way?
>
> Help appreciated.
>
> --
> Brant
> 	[[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> 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