I would like to create a function that takes a variable as an argument and uses both its values and character name within the function. For example, in the following function, I would like x to use both the values for multiplication and the name to extract appropriately extract a coefficient (note: function does not work):
frame <- data.frame(var1 = rnorm(100), var2 = rnorm(100), outcome = rnorm(100))
attach(frame)
mod <- lm(outcome ~ var1 + var2 + var1*var2)
fun <- function(x ,z, mod){
x*z*coef(summary(mod))[paste(x, z, sep = ":"), "Estimate"]
}
fun("var1", "var2", mod)
Any thoughts on how to get the function to use both attributes would be great. Thanks.
function(x,z,mod,xname=deparse(substitute(x))will give you a variable inside your function which contains the name of the input variable as a character string.