2014-10-31 47 views
0

我想創建一個函數,該函數將變量作爲參數並在函數中使用其值和字符名稱。例如,在下面的功能,我想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) 

如何得到任何想法使用這兩個屬性的功能會很好。謝謝。

+0

不清楚的地方要使用的命名項目的名稱,但'函數(X,Z,國防部,XName的= deparse(替代(X))'會給你在你的函數中包含輸入變量名稱的變量作爲字符串。 – 2014-10-31 17:33:18

回答

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 
相關問題