Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

New function to calculate conditional and marginal R2 for MixPV /WeMix #17

Open
joaomaroco opened this issue Apr 9, 2024 · 6 comments

Comments

@joaomaroco
Copy link

joaomaroco commented Apr 9, 2024

Hi Paul et al

I developed a function to calculate marginal R2 and conditional R2 from mixPV function (https://doi.org/10.1186/s40536-024-00192-0 ) on WeMix. For the r2 formulae I am using https://doi.org/10.1111/j.2041-210x.2012.00261.x eq 26 and eq 27. I am not sure I am getting the variance of fixed effects correctly, but here is a first trial:

r2 <- function(m1,df) {
  TotV <- numeric(length(m1))
  VarRcnt <- numeric(length(m1))
  VarRsch <- numeric(length(m1))
  VarF <- numeric(length(m1))
  R2cnt <- numeric(length(m1))
  R2sch <- numeric(length(m1))
  R2marg <- numeric(length(m1))
  R2cond <- numeric(length(m1))
  CoefsF <- vector()
  yFit <- vector()
  
  for (i in 1:length(m1)) {
    
    CoefsF <- m1[[i]]$coef[-1]
    
    X <- dplyr::select(df, all_of(names(CoefsF[i])))|>as.matrix()
    wX <- X*df$nwt
    yFit <- as.vector(wX%*%CoefsF)
    VarF[i] <- var(yFit, na.rm=T)
    
    TotV[i] <- sum(m1[[i]]$varDF[4])+VarF[i]
    VarRcnt[i] <- m1[[i]]$varDF[1,4]
    VarRsch[i] <- m1[[i]]$varDF[2,4]
    #VarF[i] <- sum(diag(m1[[i]]$cov_mat[-1,-1]))
    
    R2cnt[i] <- VarRcnt[i]/TotV[i]
    R2sch[i] <- VarRsch[i]/TotV[i]
    R2marg[i] <- VarF[i]/TotV[i]
    R2cond[i] <- (VarF[i]+VarRcnt[i]+VarRsch[i])/TotV[i]
  }
  
  R2m <- round(mean(R2marg), 3)
  R2c <- round(mean(R2cond), 3)
  
  Rdf <- data.frame(R2m, R2c)
  
  return(Rdf)
}

m1 is a wemix results object, and df is the original dataframe. R2m is the marginal R2, and R2c is the condtional.

@pdbailey0
Copy link
Collaborator

@joaomaroco you can test it against that package you shared. The most basic test is when all the weights are one, lmer should agree with mix.

@joaomaroco
Copy link
Author

lmer only allows weights at level 1... I guess level 2 and level 3 weights in WeMix will change the variance estimates for the random effects...

@SarahElgerby
Copy link

can any one help me with mixPV Im working with TIMMS data not Pisa

@joaomaroco
Copy link
Author

joaomaroco commented Jul 1, 2024 via email

@pdbailey0
Copy link
Collaborator

what package is mixPV in?

@joaomaroco
Copy link
Author

joaomaroco commented Jul 1, 2024 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants