我使用函数(按名称)定义一个新函数作为参数,但派生函数不起作用。发生什么事?。代码是
myfun = function(f, a){
fx = function(x) f(x)
print(fx(a)) # = f(a) OK
fp = function(x) eval( D(expression(fx), "x") )
fp(a) # = 1/2*sqrt(a) doesn't work!
}
myfun(sqrt, 4)
# console-------------------------------------------
> myfun(sqrt, 4) # = 1/2*sqrt(4) = 1/4
[1] 2
[1] 0
答案 0 :(得分:0)
我在R type conversion expression() function()找到了我的问题的答案。
我可以通过多种方式修改我的代码:
# 1. -----------------------------------
myfun = function(f, a){
g = parse(text=f) # f is string
# fx = function(x){eval(g[[1]])}
g. = D(g,"x")
fp = function(x){eval(g.)}
fp(a)
}
myfun('sqrt(x)', 4) # 0.25
# 2. -----------------------------------
fa = function(x){sqrt(x)} # with { }
fb = function(x) sqrt(x) # without { }
my2fun = function(f, a){
if(body(f)[[1]]== '{' ){
g. = D(body(f)[[2]], "x")
} else {
g. = D(as.expression(body(f)), "x")
}
fp = function(x){eval(g.)}
fp(a)
}
my2fun(fa, 4) # 0.25
# 3. And more general
fa = function(x){sqrt(x)} # with { }
fb = function(x) sqrt(x) # no { }
lafun = function(f, a){
# add { }
if(body(f)[[1]]!= '{' ) body(f) = call("{", body(f))
g. = D(body(f)[[2]], "x")
fp = function(x){eval(g.)}
print(f(a))
print(fp(a))
}
lafun(fa, 4)
lafun(fb, 4)
# 0.25
# 0.25
我需要这段代码,因为我正在使用R。
处理数值方法