创建引用变量和值的字符串名称的函数

时间:2014-10-31 16:43:07

标签: r function variables character

我想创建一个函数,该函数将变量作为参数,并在函数中使用其值和字符名称。例如,在下面的函数中,我希望x同时使用乘法值和名称来适当提取系数(注意:函数不起作用):

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)

关于如何让函数使用这两个属性的任何想法都会很棒。谢谢。

1 个答案:

答案 0 :(得分:1)

使用'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