[R] Help w/ variable names in loop with lmer

Ben Bolker bbolker at gmail.com
Mon Mar 30 00:13:24 CEST 2015


David Crow <david.crow <at> cide.edu> writes:

> 
> Hi, R users-
> 
> I'm estimating random effects models with cross-level interactions; I want
> to interact each of a vector of level-1 variables with each of a vector of
> level-2 variables.  Here's the code:
> 
> ====================
> #create data frame with level-1 variables
> k <- as.data.frame(cbind(robo, asalto, secuestro, asesinato))
> 
> #create data frame with level-2 variables
> l <- as.data.frame(cbind(IDH_IDH, IDH_ingpc, eco_pb, IM_indice, tasa_robo,
> hom_tasa, totdelitos1, totdelitos2, total, pri, pan, prd))
> 
> #get cross-level interactions
> 
> for (i in 1:length(k)) {
> for (j in 1:length(l)) {
> print(summary(lmer(hrprotcrim ~ k[,i]*l[,j] + (k[,i] | Municipio))))
> }
> }
> ======================
> 
> The code works and produces 48 (4 level-1 x 12 level-2) sets of output.
> The problem is, the output is illegible because instead of the variable
> names, I get the indices:
> 
> [output]
> ==================================
> Linear mixed model fit by REML ['lmerMod']
> Formula: hrprotcrim ~ k[, i] * l[, j] + (k[, i] | Municipio)
> 

[snip]

> Two questions:
> 
> 1)  How can I get variable names instead of indices in the above output
> 2)  How can I estimate this with "mapply" instead of the double loop?
> 
> Here's the code for "mapply"
> 
> M4 <- mapply(function(k,l){summary(lmer(hrprotcrim ~ k*l + (k |
> Municipio)))})
> 
> And here's what I get:
> 
> list()
> 

I would suggest appropriate use of ?reformulate

Assume dd is a data frame containing all variables

lev1vars <- c("robo", "asalto", "secuestro", "asesinato")
lev2vars <- c("IDH_IDH", "IDH_ingpc", ...)
ffun <- function(L1var,L2var) {
    ff <- reformulate(paste(L1var,L2var,sep="*"),
                      paste(L1var,"Municipio",sep="|"),
                      response="hrprotcrim")
    environment(ff) <- parent.frame()  ## trickiness
    return(summary(lmer(ff,data=dd)))
}
mapply(ffun,lev1vars,lev2vars)

?

If you had given a reproducible example I could have tested this ...



More information about the R-help mailing list