R scoping: disallow global variables in function

前端 未结 5 1475
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-08 23:37

Is there any way to throw a warning (and fail..) if a global variable is used within a R function? I think that is much saver and prevents unintended behaviours

5条回答
  •  误落风尘
    2020-12-08 23:57

    You can check whether the variable's name appears in the list of global variables. Note that this is imperfect if the global variable in question has the same name as an argument to your function.

    if (deparse(substitute(var)) %in% ls(envir=.GlobalEnv))
        stop("Do not use a global variable!")
    

    The stop() function will halt execution of the function and display the given error message.

提交回复
热议问题