2014-04-12 96 views
0

我一直在这个工作几个小时,我几乎卡住了。我想要一个像with函数那样的函数,但允许使用data.frame中的其他变量或外部值在我的data.frame中生成新变量。R:模拟功能内的功能

MYDATA <- data.frame(a1=rnorm(5), a2=rnorm(5)) 

dg <- function(svar, exp, tempdata="MYDATA") { 
    tempdata <- get(tempdata) 
    tempdata[svar] <- with(tempdata, eval(substitute(exp))) 
    return(tempdata) 
} 

MYDATA 
#   a1  a2 
#1 0.07113 0.84302 
#2 -0.46902 -1.12064 
#3 1.01703 0.62591 
#4 1.13271 0.24405 
#5 -0.24867 -0.02474 

理想的情况下,将做到以下几点:

dg("b",a1+a2) 
#   a1  a2  b 
#1 0.07113 0.84302 0.9141 
#2 -0.46902 -1.12064 -1.5897 
#3 1.01703 0.62591 1.6429 
#4 1.13271 0.24405 1.3768 
#5 -0.24867 -0.02474 -0.2734 

感谢您的参与! 弗朗西斯

+0

您是否在寻找'within'? – Roland

回答

1

函数体的第二行应该是:

tempdata[svar] <- eval(substitute(exp), tempdata) 
+0

非常感谢!真棒!我没有意识到我太亲近了! – fsmart