I am trying to write a custom function. I have the working code:
m <- lm(age ~ religion * degree * country + gender, WVS)
e_df <- data.frame(e <- effect("religion:degree:country", m))
e_df$predictor <- paste(e_df[,3], e_df[,2], e_df[,1], sep="\n\n") # merge first three columns
ifelse(names(e_df)=="fit", "age", names(e_df))->names(e_df) # rename column 1
print(subset(e_df, select = c(predictor, age, se)), digits = 3)
I tried to write it into the custom function:
threewaycovar<- function(outcome, V1, V2, V3, covar, d)
{require(effects)
m <- lm(outcome ~ V1 * V2 * V3 + covar, d)
e <- effect("V1:V2:V3", m)
e_df <- data.frame(e)
e_df$predictor <- paste(e_df[,3], e_df[,2], e_df[,1], sep="\n\n") # merge first three columns
ifelse(names(e_df)=="fit", "outcome", names(e_df))->names(e_df) # rename column 1
op <-(subset(e_df, select = c(predictor, outcome, se)))
return(op)}
However, the custom function keeps giving me the error message
" Error in eval(expr, envir, enclos) : object 'outcome' not found".
I am not sure why I am getting this error message. I tried to run it using
threewaycovar(WVS$age, WVS$religion, WVS$degree, WVS$country, WVS$gender, WVS)
I saw this post Error in eval(expr, envir, enclos) - contradiction? and took out a reference to column numbers that relates to outcome but my function still is not working. Can anyone tell me why my function is not working?
Edit in response to comments: WVS is a default package included in R so my data is reproducible. My traceback is
14 eval(expr, envir, enclos)
13 eval(predvars, data, env)
12 model.frame.default(outcome ~ V1 * V2 * V3 + covar + (V1 + V2 +
V3 + covar), data = structure(list(poverty = structure(c(1L, 2L, 1L, 3L, 1L, 2L, 3L, 1L, 1L, 1L, 1L, 2L, 1L, 3L, 1L, 3L, 3L, 1L, 2L, 2L, 3L, 3L, 1L, 1L, 1L, 1L, 1L, 1L, 3L, 2L, 1L, 3L, 1L, ...
11 model.frame(outcome ~ V1 * V2 * V3 + covar + (V1 + V2 + V3 +
covar), data = structure(list(poverty = structure(c(1L, 2L, 1L, 3L, 1L, 2L, 3L, 1L, 1L, 1L, 1L, 2L, 1L, 3L, 1L, 3L, 3L, 1L, 2L, 2L, 3L, 3L, 1L, 1L, 1L, 1L, 1L, 1L, 3L, 2L, 1L, 3L, 1L, 1L, ...
10 eval(expr, envir, enclos)
9 eval(call("model.frame", ff, data = data, subset = subset, na.action = naa),
envir)
8 expand.model.frame(mod, all.predictors)
7 na.omit(expand.model.frame(mod, all.predictors))
6 Analyze.model(focal.predictors, mod, xlevels, default.levels,
formula.rhs, partial.residuals = partial.residuals, quantiles = quantiles,
x.var = x.var, data = data, typical = typical)
5 Effect.lm(predictors, mod, vcov. = vcov., ...)
4 Effect(predictors, mod, vcov. = vcov., ...)
3 effect.default("V1:V2:V3", m)
2 effect("V1:V2:V3", m)
1 threewaycovar(WVS$age, WVS$religion, WVS$degree, WVS$country,
WVS$gender, WVS)
I am trying to make a function that will give me the estimated means and standard errors for a three way interaction controlling for at least one co-variate. Above is what I have tried thus far.