Jakob
Jakob

Reputation: 1463

R how to pass a function to a function

When I want to specify my own robust standard errors in a regression command like plm, how do I do this directly without running several functions?

library("plm")
library("lmtest")
Data <- iris
Data$time <- as.numeric(rep(1951:2000,3))

here is what I would run in plm:

regression <- plm(Sepal.Length ~ Sepal.Width + Petal.Length, 
    data = Data, 
    index = c("Species", "time"), 
    model = "within", 
    effect = "twoways")

now say I'd like a covariance matrix which clusters at the individual (species level):

results <- coeftest(regression,vcov=vcovHC(regression,type="HC0",cluster="group"))

My question is how I can include these standard errors directly in plm without having to run it first. This is not a big deal as the covariance matrix is calculated in a separate step anyways but would feel more elegant.

Upvotes: 0

Views: 90

Answers (2)

Helix123
Helix123

Reputation: 3697

In the plm-world, the covariance matrix is always passed as an additional argument, e.g. to summary(). But you can try the following: In the plm object, overwrite the vcov that is already there:

regression$vcov <- vcovHC(regression, type="HC0", cluster="group")

But no guarantee this does not break anything else if you apply various functions to your plm object later.

You might also want to look at the summary.plm object created by summary.plm, e.g.

res <- summary(regression, vcov = vcovHC(regression, type="HC0", cluster="group"))

Also, you might want to look at ?summary.plm (doc for summary.plm) how to pass the vcov function to summary (the example above passes the matrix the function creates).

Upvotes: 2

Hendrik D
Hendrik D

Reputation: 71

If this is a question about elegancy, try packages dplyr, (or pipeR or magrittr) for a 'pipe' operator. When writing functionA(functionB((x) or

y <- functionB(x)
z <- functionA(y)

you can use a great alternative as such:

z <- x %>% functionB %>% functionA

In your case, this would make:

results <- 
plm(Sepal.Length ~ Sepal.Width + Petal.Length, 
    data = Data, 
    index = c("Species", "time"), 
    model = "within", 
    effect = "twoways") %>% 
coeftest(., vcov=vcovHC(.,type="HC0",cluster="group"))

in which you use . to explicitly mark that you're inputting what is before the %>% pipe operator.

Upvotes: 1

Related Questions