Home > Software design >  Replace part of the output of lm() function in Base R
Replace part of the output of lm() function in Base R

Time:01-14

Object res1 is a regression function from the metafor package. Object res2 is a regression function from the stats R base.

I was wondering if it might be possible to get the vcov() of res1 and substitute it for vcov() of res2?

Below is my unsuccessful solution.

# An Example:
library(metafor)

dat2 <- escalc(measure="OR", ai=waward, n1i=wtotal, ci=maward,
n2i=mtotal, data=dat.bornmann2007)

res1 <- rma.mv(yi ~ 0 type, vi, random = ~ 1 | study/obs, data=dat2)

res2 <- lm(yi ~ 0 type, data = dat2)

vcov(res2) <- vcov(res1) ## apparently this won't work!

CodePudding user response:

You don't say how you are planning to use the result of the vcov() call, and that's crucial. If all you are doing is calling vcov() and you want a different result, simply put the metafor object as an attribute of the lm object, assign it a new class (say "lmPlusMetafor"), and define a vcov.lmPlusMetafor method to extract the result from the metafor part.

Here is the code to do this:

library(metafor)

dat2 <- escalc(measure="OR", ai=waward, n1i=wtotal, ci=maward,
n2i=mtotal, data=dat.bornmann2007)

res1 <- rma.mv(yi ~ 0 type, vi, random = ~ 1 | study/obs, data=dat2)

res2 <- lm(yi ~ 0 type, data = dat2)

attr(res2, "metafor") <- res1

class(res2) <- c("lmWithMetafor", class(res2))

vcov.lmWithMetafor <- function(object, ...) vcov(attr(object, "metafor"))

Now when you run vcov(res1) or vcov(res2) you'll get the same result.

However, this is probably not good enough for anything useful. For example, if you now run summary(res2), I think you'll see standard errors etc. based on the original values, not the metafor ones.

If you want everything to work, you'll need a lot more changes: you'll need to see how the things you want are calculated, and work out how to do them with this new "lmWithMetafor" object. It won't be easy.

CodePudding user response:

I am not sure if this will satsify what you need, but assigning the function vcov to an object may help?

vcov_1 <- vcov(res1)
vcov_2 <- vcov(res2)   

vcov_1 <- vcov_2
> vcov_1 <- vcov(res1)
> vcov_1
               typeFellowship    typeGrant
typeFellowship   0.0018436986 0.0000618297
typeGrant        0.0000618297 0.0014597749

> vcov_2 <- vcov(res2) 
> vcov_2
               typeFellowship  typeGrant
typeFellowship    0.008567784 0.00000000
typeGrant         0.000000000 0.00556906


> vcov_1 <- vcov_2
> vcov_1
               typeFellowship  typeGrant
typeFellowship    0.008567784 0.00000000
typeGrant         0.000000000 0.00556906

  •  Tags:  
  • Related