有哪些方法可以在 R 中编辑函数? [英] What ways are there to edit a function in R?

查看:23
本文介绍了有哪些方法可以在 R 中编辑函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有以下功能:

foo <- function(x)
{
    line1 <- x
    line2 <- 0
    line3 <- line1 + line2
    return(line3)
}

我们想把第二行改为:

    line2 <- 2

你会怎么做?

一种方法是使用

fix(foo)

并更改功能.

另一种方法是重新编写函数.

Another way is to just write the function again.

还有别的办法吗?(记住,任务只是改变第二行)

Is there another way? (Remember, the task was to change just the second line)

我想要的是某种方式将函数表示为字符串向量(好吧,字符),然后更改其中一个值,然后再次将其转换为函数.

What I would like is for some way to represent the function as a vector of strings (well, characters), then change one of it's values, and then turn it into a function again.

推荐答案

或者看看调试函数trace().它可能不是您正在寻找的东西,但它可以让您尝试更改,并且它具有很好的功能,您可以随时使用 untrace() 返回到您的原始函数.trace()base 包的一部分,并带有一个漂亮而详尽的帮助页面.

Or take a look at the debugging function trace(). It is probably not exactly what you are looking for but it lets you play around with the changes and it has the nice feature that you can always go back to your original function with untrace(). trace() is part of the base package and comes with a nice and thorough help page.

首先调用 as.list (body(foo)) 来查看所有代码行.

Start by calling as.list (body(foo)) to see all the lines of your code.

as.list(body(foo))
[[1]]
`{`

[[2]]
line1 <- x

[[3]]
line2 <- 0

[[4]]
line3 <- line1 + line2

[[5]]
return(line3)

然后,您只需通过在 trace() 中定义参数来定义要添加到函数中的内容以及放置它的位置.

Then you simply define what to add to your function and where to place it by defining the arguments in trace().

trace (foo, quote(line2 <- 2), at=4)
foo (2)
[1] 4

我一开始就说过 trace() 可能不是您要查找的内容,因为您并没有真正更改第三行代码,而是简单地将值重新分配给对象 line2 在下面,插入了一行代码.如果你把你现在跟踪的函数的代码打印出来就更清楚了

I said in the beginning that trace() might not be exactly what you are looking for since you didn't really change your third line of code and instead simply reassigned the value to the object line2 in the following, inserted line of code. It gets clearer if you print out the code of your now traced function

body (foo)
{
    line1 <- x
    line2 <- 0
    {
        .doTrace(line2 <- 2, "step 4")
        line3 <- line1 + line2
    }
    return(line3)
}

这篇关于有哪些方法可以在 R 中编辑函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆