[R] Trying to learn how to write an "advanced" function

Berwin A Turlach berw|n@tur|@ch @end|ng |rom gm@||@com
Thu Mar 16 16:19:33 CET 2023


G'day John,

For these snippets to produce what I think you want them to produce it
is just necessary to define doit() as follows:

doit <- function(x){
 lm(formula=x)
}


R> # run formula y~x
R> JD <- doit(y~x)
R> JD

Call:
lm(formula = x)

Coefficients:
(Intercept)            x  
     0.8403       0.8558  

R> # run formula y~x+z
R> JD2 <- doit(y~x+z)
R> JD2

Call:
lm(formula = x)

Coefficients:
(Intercept)            x            z  
    -0.7490       0.6237       1.9023  


Cheers,

	Berwin


On Thu, 16 Mar 2023 14:53:33 +0000
"Sorkin, John" <jsorkin using som.umaryland.edu> wrote:

> Although I owe thanks to Ramus and Ivan, I still do not know how to
> write and "advanced" function. 
> 
> My most recent try (after looking at the material Ramus and Ivan set)
> still does not work. I am trying to run the lm function on two
> different formulae: 1) y~x, 2) y~x+z
> Any corrections would be appreciated!
> 
> Thank you,
> John
> 
> 
> doit <- function(x){
>   ds <- deparse(substitute(x))
>   cat("1\n")
>   print(ds)
>   eval(lm(quote(ds)),parent.frame())
> }
> 
> # define data that will be used in regression
> y <- 1:10
> x <- y+rnorm(10)
> z <- c(rep(1,5),rep(2,5))
> # Show what x, y  and z look like
> rbind(x,y,z)
> 
> # run formula y~x
> JD <- doit(y~x)
> JD
> 
> # run formula y~x+z
> JD2 <- doit(y~x+z)
> JD2



More information about the R-help mailing list