S******y 发帖数: 1123 | 1 Does R function pass parementer by reference or by copy?
Can R do both?
Some light shed on this will be appreciated! | S******y 发帖数: 1123 | 2 Thanks. An-dong!
Can you provide a specific example? | t*****9 发帖数: 19 | 3 you may try this simple code (i seldom this job, we may keep an eye on the
variables very often)
pass <- function(a,b){
cat(a<-a+1,"\t");
cat(b<<-b+1,"\n");
}
a <- 10;
b <-10;
for(i in 1:3){
pass(a,b);
cat(a,"\t")
cat(b,"\n\n");
}
HTH | S******y 发帖数: 1123 | 4 Thanks so much!
That is the best example I have ever seen on this topic! | q**j 发帖数: 10612 | 5 i just looked at the R help doc, it seems to me that the "<<-" operator will
only work this way when you do not have a variable called 'b' in the functi
on defined. so i am not fully convinced that this qualifies as a passing by
reference.
Can you come up with an example w/o the need to define a function? I mean on
ly at the top level, i.e., global environment? Thanks.
【在 t*****9 的大作中提到】![](/moin_static193/solenoid/img/up.png) : you may try this simple code (i seldom this job, we may keep an eye on the : variables very often) : pass <- function(a,b){ : cat(a<-a+1,"\t"); : cat(b<<-b+1,"\n"); : : } : a <- 10; : b <-10; : for(i in 1:3){
| q**j 发帖数: 10612 | 6 like this case:
> a = 10
> b <<- a
> b
[1] 10
> a = 2
> b
[1] 10
if it is by reference, i got the memory location of a, so its value should c
hange after we reassign 2 as a's value. but it did not change.
will
functi
by
on
【在 q**j 的大作中提到】![](/moin_static193/solenoid/img/up.png) : i just looked at the R help doc, it seems to me that the "<<-" operator will : only work this way when you do not have a variable called 'b' in the functi : on defined. so i am not fully convinced that this qualifies as a passing by : reference. : Can you come up with an example w/o the need to define a function? I mean on : ly at the top level, i.e., global environment? Thanks.
| g********r 发帖数: 8017 | 7 THat' the downside of R. I've seen some functions pass by reference, some by
copy, depending on whose
package you are using. I think it is safe to assume it's passed by copy if
the help didn't say otherwise.
【在 S******y 的大作中提到】![](/moin_static193/solenoid/img/up.png) : Does R function pass parementer by reference or by copy? : Can R do both? : Some light shed on this will be appreciated!
| t*****9 发帖数: 19 | 8 However, if we don't have a super large data set to deal with or have tight
memory budget, we really don't need to do this. Do the normal way is of
course, safe and sufficient, I believe. |
|