0

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.

1
  • Not clear where you want the named item's name to be used, but 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. Commented Oct 31, 2014 at 17:33

1 Answer 1

1

Use 'get':

> fun <- function(x ,z, mod){
+      get(x)*get(z)*coef(summary(mod))[paste(x, z, sep = ":"), "Estimate"] 
+ }
> 
> fun("var1", "var2", mod)
  [1] -0.0080282899 -0.0375760528  0.1314646270 -0.3136248175 -0.0912983779  0.5771128233  0.0734350308  0.0215545200
  [9] -0.0049817704  0.0656309765 -0.0685989980  0.1600126096  0.1881071369  0.0016444350 -0.2188112562 -0.3690306926
 [17] -0.1379712449  0.0228213359  0.0195600421 -0.0055658169 -0.0239113219 -0.0020960696  0.0932547018 -0.0022087797
 [25]  0.0020928153 -0.2090844569  0.0457279404  0.2494709220 -0.0717376049 -0.0408030910  0.3326227397 -0.0192946052
 [33] -0.2021269287  0.0113860642 -0.1203568228  0.0100945335  0.0422798371 -0.1247580314  0.0435195061 -0.0852773981
 [41] -0.0303572418 -0.3540273388 -0.0002004216  0.1483439765  0.1329019528  0.2411258412  0.0961413629 -0.0635466539
 [49]  0.1110941733  0.0087394442  0.0288497043 -0.1566687438  0.1774317264 -0.0359233185 -0.0921803037  1.0297600232
 [57]  0.3894044075  0.0373172397  0.0298195653  0.1932384455 -0.0594339135 -0.0078471172 -0.0137532570 -0.2904056568
 [65] -0.5956431258 -0.0130037130  0.0475808502  0.0515916115 -0.0226011496  0.0490032490  0.1846703925 -0.0867655096
 [73] -0.0009076219 -0.0166261367 -0.3937592477 -0.5620182629 -0.0125819895 -0.0595718019 -0.3740056323 -0.4656389032
 [81] -0.4234212514 -0.0629969243 -0.3768155432  0.0836941608 -0.1289267765  0.2155533967 -0.5705043983  0.1460241809
 [89]  0.2649009528  0.0088861310 -0.0467066205  0.2067550374 -0.0523530229 -0.1531239977 -0.0221151949 -0.1828452413
 [97]  0.0010752685  0.1656129949 -0.5446105206  0.1123525128
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.