Hello,

There is a "standard" deparse/substitute trick that gets the names of the variables passed to a function. There are more sophisticated ways but maybe that is what you are looking for.


myfunction <- function(y, x, dataframe){
  y <- deparse(substitute(y))
  x <- deparse(substitute(x))
  fmla <- as.formula(paste(y, '~', x))
  fit0 <- lm(fmla, data = dataframe)
  summary(fit0)
}

# Run the function using dep and ind as dependent and independent variables.
mydata <- data.frame(dep = c(1,2,3,4,5),ind=c(1,2,4,5,7))
myfunction(dep, ind, mydata)

# Run the function using outcome and predictor as dependent and independent variables.
newdata <- data.frame(outcome=c(1,2,3,4,5),predictor=c(1,2,4,5,7))
myfunction(outcome, predictor, newdata)


Note: your function has an argument 'dataframe' that you didn't use in any of the two calls.


Hope this helps,

Rui Barradas

Às 02:22 de 09/05/19, Sorkin, John escreveu:
Can someone send me something I can read about passing parameters so I can 
understand how lm manages to have a dataframe passed to it, and use columns 
from the dataframe to set up a regression. I have looked at the code for lm and 
don't understand what I am reading. What I want to do is something like the 
following,


myfunction <- function(y,x,dataframe){

   fit0 <- lm(y~x,data=dataframe)
   print (summary(fit0))
}

# Run the function using dep and ind as dependent and independent variables.
mydata <- data.frame(dep=c(1,2,3,4,5),ind=c(1,2,4,5,7))
myfunction(dep,ind)
# Run the function using outcome and predictor as dependent and independent 
variables.
newdata <- data.frame(outcome=c(1,2,3,4,5),predictor=c(1,2,4,5,7))
myfunction(outcome,predictor)





John David Sorkin M.D., Ph.D.
Professor of Medicine
Chief, Biostatistics and Informatics
University of Maryland School of Medicine Division of Gerontology and Geriatric 
Medicine
Baltimore VA Medical Center
10 North Greene Street
GRECC (BT/18/GR)
Baltimore, MD 21201-1524
(Phone) 410-605-7119
(Fax) 410-605-7913 (Please call phone number above prior to faxing)


        [[alternative HTML version deleted]]

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


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

Reply via email to