Simon Harmel
Simon Harmel

Reputation: 1489

Modify three lines of code in a function from an R package

function Effect.lm() from R package effects has a bug that can be resolved by adding 3 lines of code.

I have the solution below, but is there a way to implement this change to Effect.lm() from R package effects?

I intend to use Effect.lm() indirectly (via another function), and the change must be replicable by other users.

ps. I think this answer may be relevant. Unfortunately, @Ben Bolker 's answer (his R code), as he mentions, doesn't achieve my goal above.

library(effects)

# Delete line 164 in the following
View(effects::Effect.lm)

# Then, in its place, add the following 3 lines

  use <- !is.na(mod$coefficients)     # new
  mmat <- mod.matrix[, use]           # new
  if (any(is.na(V))) V <- V[use, use] # new

Upvotes: 1

Views: 256

Answers (1)

Ben Bolker
Ben Bolker

Reputation: 226871

The easiest way to do this is to download the package source, edit the source appropriately, then run R CMD INSTALL to install the modified package.

If your workflow only needs to call Effect.lm directly (i.e. not indirectly through other package functions), then you can use dump() to dump the function definition to a file, edit the file, then source() it.

There are tricks involving turning the body of the function into a character vector, editing it, and replacing it, something like

oldfun <- effects:::Effect.lm
## this is the 165th line of the *body*
replace_line <- 165
s <- deparse(body(oldfun))
new_lines <- c("use <- !is.na(mod$coefficients)",
               "mmat <- mod.matrix[, use]",
               "if (any(is.na(V))) { V <- V[use, use] } ")
s <- c(s[1:(replace_line-1)], new_lines, s[(replace_line+1):length(s)])
newfun <- oldfun
body(newfun) <- parse(text=s)

but this is clever and fragile and will not work if you're trying to replace the function within a package environment (or, it may work, but only after a lot of messing around with trying to unlock environments etc.).

Or you could e-mail the maintainer and ask them to fix the bug ...

Upvotes: 5

Related Questions