Hi. I'm trying to find a systematic way to prevent assignment to names of existing functions. I've tried reassigning to the assignment operator, with mixed results. The function definition for "<-" below works as hoped for the demonstrated assignments to a and c. However, for the assignment based on the test function, it appears that the formal argument is not visible. Any suggestions? Thanks, Tim. ------------------------------------------------------------- rm(list=ls()) "<-" <- function(x,value){ try(assign("y",x), silent=TRUE) if (exists("y", mode="function")) stop("assignment to an existing function") else eval(substitute(.Primitive("<-")(x, value)),sys.frame(sys.parent(2))) } MYLEN <- function(infile){ LEN <- nchar(infile) return(LEN) } a <- 3 c <- 3 #Error in c <- 3 : assignment to an existing function d <- MYLEN("word") #Error in nchar(infile) : object "infile" not found
On Thu, 6 Apr 2006, Tim Bergsma wrote:> Hi. > > I'm trying to find a systematic way to prevent assignment to names of > existing functions. I've tried reassigning to the assignment operator, > with mixed results. The function definition for "<-" below works as > hoped for the demonstrated assignments to a and c. However, for the > assignment based on the test function, it appears that the formal > argument is not visible. Any suggestions? >Well, my first suggestion would be not to do it. I don't see any real benefit, and messing around with something as basic as assignment is likely to break something. If nothing else, there is certainly code out there where people have, say, "df" or "c" as a variable name, and it isn't doing any harm. As a programming exercise it seems that the following works "<-" <- function(x,value){ if(tryCatch(is.function(x),error=function(e) FALSE)) stop("assignment to an existing function") else eval.parent(substitute(.Primitive("<-")(x,value))) } -thomas Thomas Lumley Assoc. Professor, Biostatistics tlumley at u.washington.edu University of Washington, Seattle
Tim Bergsma <timb at metrumrg.com> writes:> Hi. > > I'm trying to find a systematic way to prevent assignment to names of > existing functions.An alternative would be to put your functions into an R package with a namespace. Then you won't be able to overwrite them (easily). + seth