What ways are there to edit a function in R?

2019-01-03 06:16发布

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.

5条回答
闹够了就滚
2楼-- · 2019-01-03 06:23

fixInNamespace is like fix, for functions in a package (including those that haven't been exported).

查看更多
狗以群分
3楼-- · 2019-01-03 06:24
> body(foo)[[3]] <- substitute(line2 <- 2)
> foo
function (x) 
{
    line1 <- x
    line2 <- 2
    line3 <- line1 + line2
    return(line3)
}

(The "{" is body(foo)[[1]] and each line is a successive element of the list.)

查看更多
smile是对你的礼貌
4楼-- · 2019-01-03 06:27

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.

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 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)
}
查看更多
放我归山
5楼-- · 2019-01-03 06:33

You can use the 'body' function. This function will return the body of function:

fnx = function(a, b) { return(a^2 + 7*a + 9)}
body(fnx)
# returns the body of the function

So a good way to 'edit' a function is to use 'body' on the left-hand side of an assignment statement:

body(fnx) = expression({a^2 + 11*a + 4})
查看更多
手持菜刀,她持情操
6楼-- · 2019-01-03 06:44

fix is the best way that I know of doing this, although you can also use edit and re-assign it:

foo <- edit(foo)

This is what fix does internally. You might want to do this if you wanted to re-assign your changes to a different name.

查看更多
登录 后发表回答