有关重命名功能的问题

时间:2020-10-13 19:03:20

标签: r function derivative

我正在编写一些代码来计算函数的派生类。我设法为1个变量生成一阶和二阶导数,并作为函数存储在环境中,因此以后可以对其进行绘制。现在,我正在尝试计算具有2个或更多变量的方程的偏导数,而我找不到能够在环境中生成与该函数的偏导数一样多的代码。

为了澄清,我使用了1个变量:

    f <- function(x) cos(20*x)*exp(-1*x)
    F.<- function (x) eval(D(as.expression(body(f)), "x"))
    F..<- function (x) eval(D(as.expression(D(as.expression(body(f)), "x")),"x"))

并且运行良好,我在环境中获得了3个功能: functions

但是对于多个变量,我必须遍历此函数并生成与方程的偏导数一样多的函数。

我的问题是:如何生成一个循环,以计算函数的偏导数并将其存储为函数,每个都有一个自定义名称?

我在for循环中尝试了导数函数,但无法为每次导数计算定义不同的名称:

    for (i in 1:nro_variables) {
      var_D = vector_variables[i]  
      F.<- function (x) eval(D(as.expression(body(f)), var_D))
    }

2 个答案:

答案 0 :(得分:2)

类似于避免使用分配许多单独的相似对象来泛滥全局环境的方法,请考虑使用可以为元素建立索引的单个列表,以更好地进行串行组织。请参阅@GregorThomas的最佳做法answer,主张:

永远不要首先创建d1 d2 d3,...,dn。创建包含d个元素的列表n

具体来说,如果vector_variables是字符向量,则sapply使用simplify=FALSE将返回函数的命名列表。是的,仍然可以调用列表中的函数。

partial_deriv_funcs <- sapply(vector_variables, function(var_D) {
    f <- function(x) cos(20*x)*exp(-1*x)
    return(function(x) eval(D(as.expression(body(f)), var_D)))
}, simplify = FALSE)

单个或迭代地调用函数元素:

# CALL SINGLE FUNCTION WITH SINGLE PARAM
result <- partial_deriv_funcs[['var1']](param)

# CALL SAME FUNCTION WITH VECTOR OF PARAMS
results <- lapply(param_vector, partial_deriv_funcs[['var1']])

# CALL ALL FUNCTIONS USING SAME PARAM
results <- lapply(partial_deriv_funcs, function(f) f(param))

# CALL ALL FUNCTIONS EACH WITH DIFFERENT PARAM
results <- mapply(function(f,p) f(p), partial_deriv_funcs, param_per_func_vector, SIMPLIFY= FALSE)
results <- Map(function(f,p) f(p), partial_deriv_funcs, param_per_func_vector) # EQUIVALENT

答案 1 :(得分:1)

vocations.json[ "Accessory designer", "Acoustical engineer", "Acrobat", "Actor", "Actress", "Advertising designer", "Aeronautical engineer", "Aerospace engineer", "Agricultural engineer", "Anesthesiologist", "Anesthesiologist Assistant", "Animator", "Anthropologist", "Applied engineer", "Arborist", "Archaeologist", "Archimime", "Architect", "Army officer", "Art administrator", "Artisan", [...] ] 可用于定义函数,而<!DOCTYPE html> <html lang = "en"> <head> <meta charset = "UTF-8"> <title>testform</title> <link rel = "stylesheet" href = "test2.css"> <style> .enrol_class { display: flex; flex-direction: row, align-items: center} </style> </head> <body> <div class='enrol_class'> <ul> <li> <input type = "radio" id = "rad_1" name = "classes" class = "radio_btn"> <label for="rad_1">Class 1</label> </li> <li> <input type = "radio" id = "rad_2" name = "classes" class = "radio_btn"> <label for="rad_2">Class 2</label> </li> <li> <input type = "radio" id = "rad_3" name = "classes" class = "radio_btn"> <label for="rad_3">Class 3</label> </li> </ul> <button type = "button" id = "enrol_btn" style='margin-left: 20px'>ENROL</button> </div> </body>可为其指定正确的名称。

eval