[R] scope of variables in R
Sigbert Klinke
sigbert at wiwi.hu-berlin.de
Tue Mar 31 14:35:47 CEST 2009
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
Hi,
A) you should give and return the variables through input/output
parameter of the functions, e.g.
pwtset <- function(n, inout) {
if (n < 100){
inout$ncof <- n
} else {
inout$ncof <- n -100
}
...
return(inout)
}
ford <- function(inout) {
...
n <- 104
inout <- pwtset(n, inout)
print(inout$ncof)
...
return (inout)
}
inout <- list(ncof=0, ioff=0, joff=0, sig=0.0)
inout <- ford(inout)
...
B) If you really need access to the global variables then use "assign"
and "get"
pwtset <- function(n) {
if (n < 100){
ncof <- n
} else {
ncof <- n -100
}
assign ("ncof", ncof, envir=.GlobalEnv)
...
return(inout)
}
ford <- function(inout) {
...
n <- 104
inout <- pwtset(n, inout)
ncof <- get("ncof", envir=.GlobalEnv)
print(ncof)
...
}
...
ford()
...
This programing style has a serious disadvantage: Debugging can become
very difficult, since the value of ncof in .GlobalEnv might not be what
you expect.
Yours sincerely
Sigbert
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.6 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org
iD8DBQFJ0g4jWvYUYQkj1zkRAiopAJ49Vo+NriS+R7/24QGwtPB43wI/HQCdGvYE
PjgZ+Vn0P30D5S3WvJrMX9s=
=e9rL
-----END PGP SIGNATURE-----
More information about the R-help
mailing list