When we assign the value of a variable to another variable in R, they would share the same memory location before they have different values. This saves the memory but sometime can cause trouble. For example, if I assign the value of variable a0 to variable b0 and then pass both a0 and b0 to an Rcpp function by reference, changing the value of a0 in the function would cause undesired change of b0. I need to make extra copy of b0 before the change of a0 to hold the value.
To avoid the trouble described above, using as.numeric() (for vectors) and data.frame() for (dataframes) to assign value of one variable to another would force R to make a copy at a separate memory location. However, this does not work for length 1 vector (scalar).
a0=1:3
b0=a0
c0=as.numeric(a0)
tracemem(a0) == tracemem(b0)#TRUE
tracemem(a0) == tracemem(c0)#FALSE
a0=4
b0=a0
c0=as.numeric(a0)
tracemem(a0) == tracemem(b0)#TRUE
tracemem(a0) == tracemem(c0)#TRUE
I think there are some work-around like making an extra copy to hold the value or do a simple plus and minus change to the scalar to make the values different. But I am wondering how people usually deal with this problem.
Just find that as.numeric(a0)[1] would create a copy at different memory location