I’m trying to write a predict style function for lme4’s lmer models. The idea is that the predict function will work on a dataframe containing factor and variable levels, of the kind produced by expand.grid:
level_df <- expand.grid(a=1:3, b=4:6)
I’m at the point where I can get the formula for calculating a given effect/interaction as a string:
formula_string <- "a * b + 3"
But the only way I’ve been able to apply that formula to the level dataframe (in this case, evaluating the formula for each value of a and b) is through some pretty liberal and probably dangerous use of things like assign and eval:
EffectFunction <- function(df_row, formula_string) {
l_cols <- colnames(df_row)
for (i in 1:ncol(df_row)) {
assign(l_cols[i], df_row[1, i])
}
parsed <- parse(text=formula_string)
df_row$effect_val <- eval(parsed)
return(df_row)
}
pred_results <- adply(
level_df,
1,
formula_string=formula_string,
EffectFunction
)
Are there safer and faster ways to convert between strings and symbols/variable names?
You can use a
data.frameas the envir argument forevalso
should work nicely as it will look (first) within
level_dffor any variables.