[R] Bug? assigning with operator '=' to local parameter changes object in global environment?

oehl_list@gmx.de oehl_list at gmx.de
Tue May 21 17:22:51 CEST 2002


			   [needed manual approvement by MM
			    original `Subject' had was caught as potential spam]

I had problems with a function non-intendedly changing a global variable. It
turned out to be a consequence of using the assignment operator '=' from
within the function. I am wondering, wether this is considered a bug? On the one
hand the help text does not appear to define a behaviour of '=' from within
functions, anyhow, isn't it a bit dangerous? 

# replication code at end of mail

> # no problem here
> a <- list(a1=1)
> t1 <- function(a){
+ 	a$a1 <- 3  # here we assign to a local copy of global a
+ 	a
+ }
> a2 <- t1(a)
> a
$a1
[1] 1

> a2
$a1
[1] 3

> 
> 
> # problem here
> t2 <- function(a){
+ 	a$a1 = 3  # here we THINK we assign to a local copy of global a
+ 	a
+ }
> a2 <- t2(a)
> a
$a1
[1] 3

> a2
$a1
[1] 3

> # however IN FACT WE ASSIGNED to GLOBAL a !!! 

If this is intended, the help text should perhaps be more clear about it.
If it is not intended, it might be a good idea to either change the
behaviour or catch such usage as an error, because some people switching between many
languages easily mix up assignment operators. 

Best



Jens Oehlschlägel



# replication code


# no problem here
a <- list(a1=1)
t1 <- function(a){
	a$a1 <- 3  # here we assign to a local copy of global a
	a
}
a2 <- t1(a)
a
a2


# problem here
t2 <- function(a){
	a$a1 = 3  # here we THINK we assign to a local copy of global a
	a
}
a2 <- t2(a)
a
a2
# however IN FACT WE ASSIGNED to GLOBAL a !!! IS THIS INTENDED? IT IS
DANGEROUS !!



--please do not edit the information below--

Version:
 platform = i386-pc-mingw32
 arch = i386
 os = mingw32
 system = i386, mingw32
 status = 
 major = 1
 minor = 5.0
 year = 2002
 month = 04
 day = 29
 language = R

Windows 2000 Professional (build 2195) Service Pack 1.0

Search Path:
 .GlobalEnv, package:ctest, Autoloads, package:base

-- 
GMX - Die Kommunikationsplattform im Internet.
http://www.gmx.net

-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list