有什么方法可以编辑R中的函数? [英] What ways are there to edit a function in R?
问题描述
foo < - function(x)
{
line1< - x
line2< - 0
line3< - line1 + line2
return(line3)
}
而且我们希望将第二行更改为:
line2 < - 2
你会怎么做?
一种方法是使用
fix(foo)
并改变函数。
另一种方法是只写函数再次。
有另一种方法吗? (记住,任务只是改变第二行)
我想用某种方式将函数表示为字符串向量(以及字符) ,然后改变其中一个值,然后再次将它变成一个函数。
解决方案或者看看调试功能
迹()
。它可能不是你正在寻找的东西,但它可以让你玩弄变化,它具有很好的特性,你可以随时回到你的原始函数untrace()
。
trace()
是base
包的一部分,并且附带了一个很好且彻底的帮助页面。
首先调用
as.list(body(foo))
来查看代码的所有行。 / p>
as.list(body(foo))
pre>
[[1]]
`{`
[[2]]
line1 < - x
[[3]]
line2 < - 0
[[4]]
line3< - line1 + line2
[[5]]
return(line3)
然后,通过定义
trace()$ c $中的参数,简单地定义要添加到函数中的内容以及放置位置
$ btrace(foo,quote(line2 < - 2),at = 4)
foo( 2)
[1] 4
我在开始时说
trace()
可能不是你正在寻找的,因为你没有真正改变你的第三行代码,而是简单地将值重新分配给对象line2 code>在以下插入的代码行中。如果你打印出你现在被追踪的函数的代码,它会变得更清楚。
body(foo)
{
line1 < - x
line2 < - 0
{
.doTrace(line2 < - 2,step 4)
line3 < - line1 + line2
}
return(line3)
}
Let's say we have the following function:
foo <- function(x) { line1 <- x line2 <- 0 line3 <- line1 + line2 return(line3) }
And that we want to change the second line to be:
line2 <- 2
How would you do that?
One way is to use
fix(foo)
And change the function.
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.
解决方案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 withuntrace()
.trace()
is part of thebase
package and comes with a nice and thorough help page.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)
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
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 objectline2
in the following, inserted line of code. It gets clearer if you print out the code of your now traced functionbody (foo) { line1 <- x line2 <- 0 { .doTrace(line2 <- 2, "step 4") line3 <- line1 + line2 } return(line3) }
这篇关于有什么方法可以编辑R中的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!