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

Sorkin, John j@ork|n @end|ng |rom @om@um@ry|@nd@edu
Thu Mar 16 15:53:33 CET 2023

```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

________________________________________
From: R-help <r-help-bounces using r-project.org> on behalf of Rasmus Liland <jral using posteo.no>
Sent: Thursday, March 16, 2023 8:42 AM
To: r-help
Subject: Re: [R] Trying to learn how to write an "advanced" function

On 2023-03-16 12:11 +0000, Sorkin, John wrote:
> (1) can someone point me to an
> explanation of match.call or match
> that can be understood by the
> uninitiated?

Dear John,

the man page ?match tells us that match
matches the first vector against the
second, and returns a vector of indecies
the same length as the first, e.g.

> match(c("formula", "data", "subset", "weights", "na.action", "offset"), c("Maryland", "formula", "data", "subset", "weights", "na.action", "offset", "Sorkin", "subset"), 0L)
 2 3 4 5 6 7

> (2) can someone point me to a document
> that will help me learn how to write

Perhaps the background here is looking
at the lm function as a basis for
the exercise becomes looking at
dput(lm), understanding every line by
looking up all the functions you do not
understand in the man pages e.g. ?match.
Remember, you can search for things
inside R by using double questionmark,
??match, finding versions of match
existing inside other installed
packages, e.g.  raster::match and
posterior::match, perhaps this exercise
becomes writing ones own version of lm
inside ones own package?

Best,
Rasmus

______________________________________________
R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see