0

I came across this code

fm <- y ~ x
mods <- setNames(as.list(1:4), paste0("lm", 1:4))
# loop over the four datasets in the quartet
for(i in 1:4) {
  fm[2:3] <- lapply(paste0(c("y","x"), i), as.name)
  mods[[i]] <- lmi <- lm(fm, data=anscombe)

I guessed the ~ in this case referring to the linear relationship between y and x, but what is its "overall" meaning?

Also, what exactly is the variable fm and what does the index [2:3] (as in fm[2:3]) refer to? Can someone please explain?

Nemo
  • 1,124
  • 2
  • 16
  • 39
  • 8
    `help("formula")` .... – Ben Bolker Jun 20 '23 at 23:59
  • 1
    If you look at `as.character(fm)`, you'll see `c("~", "y", "x")`, which means that `fm[2:3] <- ...` is doing simple index replacement: it replaces `"y"` and `"x"` with the results of the RHS (while keeping it as a formula, that is). This should be further clear when looking at `fm` both before and after that sub-assignment. – r2evans Jun 21 '23 at 00:48
  • Help pages also accessible with `?tilde`, `?"~"`, etc. – Gregor Thomas Jun 21 '23 at 01:10
  • Thanks @r2evans for the tips. That's most helpful for people like me. I didn't know that it's possible to look "inside" the variable `fm`. – Nemo Jun 22 '23 at 01:19

0 Answers0