Using clustered covariance matrix in predict.lm()

前端 未结 2 566
心在旅途
心在旅途 2021-02-09 00:04

I am analyzing a dataset in which data is clustered in several groups (towns in regions). The dataset looks like:

R> df <- data.frame(x = rnorm(10), 
             


        
2条回答
  •  甜味超标
    2021-02-09 00:32

    I modified the above code slightly to be more consistent with the predict function--this way you are not expected to enter values for the outcome in the newdata dataframe

    predict.rob <- function(x,clcov,newdata){
    if(missing(newdata)){ newdata <- x$model }
    tt <- terms(x)
    Terms <- delete.response(tt)
    m.mat <- model.matrix(Terms,data=newdata)
    m.coef <- x$coef
    fit <- as.vector(m.mat %*% x$coef)
    se.fit <- sqrt(diag(m.mat%*%clcov%*%t(m.mat)))
    return(list(fit=fit,se.fit=se.fit))}
    

提交回复
热议问题