Your approach seems reasonable to me, though I wouldn't do it that way.

The way I work this sort of thing out is to get R to do a simple example, then see what it did, and duplicate that.

For example,

  f <-  ~ (Heigh + Ho + Silver + Away)^2

Then look at as.list(f), as.list(f[[2]]), as.list(f[[c(2,2)]]), etc., and reproduce that structure.

So I can reproduce that with

  f <- ~(Heigh)^2
  f[[c(2,2,2)]] <- call("+", f[[c(2,2,2)]], as.name("Ho"))
  f[[c(2,2,2)]] <- call("+", f[[c(2,2,2)]], as.name("Silver"))
  f[[c(2,2,2)]] <- call("+", f[[c(2,2,2)]], as.name("Away"))

and there are obvious ways to convert that to work with names in a vector.

Duncan Murdoch

On 2025-03-29 5:30 p.m., Bert Gunter wrote:
Note: I am almost certain that this has been asked and answered here
before, so my apologies for the redundant query.

I also know that there are several packages that will do this, but I wish
to do it using base R functions only (see below).

The query: Suppose I have a character vector of names like this:
somenames <- c("Heigh", "Ho", "Silver", "Away")
(maybe dozens or hundreds: i.e. lots of names)

Now suppose want to put these in a model formula like this:
~ (Heigh + Ho + Silver + Away)^2

... But **without** pasting them into a character vector and using
parse(text = ...) , which, I grant, is sometimes the simplest way.
Instead, I want to do it using Base R's computing on the language
functions. I can do this with bquote() or substitute(), for example, like
this:

somenames <- c("Heigh", "Ho", "Silver", "Away")
nms <- lapply(somenames, as.name)
form <- nms[[1]]
for(x in nms[-1])
    form <<- bquote(.(form) + .(x), list(form = form, x = x))
## or form <<- substitute(form + x, list(form = form, x = x))
form <- bquote(~ (.(form))^2, list(form =form))

## yielding
form
~(Heigh + Ho + Silver + Away)^2

My question: Is there a simpler/slicker way to do this? This seems kinda
kludgy, and I have the feeling that I'm missing something obviously better
(in base R only; obviously better stuff is in various packages)

Best to all,
Bert

"An educated person is one who can entertain new ideas, entertain others,
and entertain herself."

        [[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 https://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 https://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to