Causing a copy of a function, rather than a pointer to it, to be assigned to a variable name.

Normally, assignment in R makes a copy. For example, in

bar <- "aaa"
foo <- bar
foo <- "bbb"

the last line doesn't change the variable bar in any way. But consider the following reprex. Let's say there's a function

foo1 <- function(x, y){
z <- (x - y)
return((x - y) / z)

which gives me these results:

foo1(1, 5)
[1] 1
foo1(7, 9)
[1] 1
foo1(1, 1)
[1] NaN

Suppose that foo1 is not the reprex I have here, but some long, complicated function where the reason for the unexpected result is not immediately clear, so in order to understand the problem, I need to run it a line at a time. Suppose further that for whatever reason (e.g it's code that someone else is responsible for), I don't want to tamper with foo1 itself, only to understand what went wrong with the input I gave it (e.g., in the reprex, the two arguments can't be equal if you require that the value returned be 1). So I try the following:

foo2 <- foo1

I go into debug mode, understand that the two arguments have to be different, then remove my copy of the function...


...and think I'm done. But then when I do


I go into debug mode

debugging in: foo1(1, 1.01)

because, if I understand aright, my assignment of foo1 to foo2 just created a pointer, not a true copy. So when I did


it put foo1, which I didn't want to change in any way, into debug mode. Is there a way to get R to do copy-on-assignment when I use the assignment operator with a function, so that I create a new function which is identical to the old one in its content but has a different memory location?

data.table::copy() will force R to make a copy:


a <- setdiff
a(1, 1)       # Goes into debug mode
setdiff(1, 1) # Nothing happens
a(1, 1)       # Goes into debug mode

Of course, for your specific example, you can use debugonce(foo1).


This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.