In R, what exactly is the problem with having variables with the same name as base R functions?

后端 未结 7 1388
深忆病人
深忆病人 2020-11-30 03:48

It seems to be generally considered poor programming practise to use variable names that have functions in base R with the same name.

For example, it is tempting to

7条回答
  •  北荒
    北荒 (楼主)
    2020-11-30 04:28

    R is very robust to this, but you can think of ways to break it. For example, consider this funcion:

    foo <- function(x,fun) fun(x)
    

    Which simply applies fun to x. Not the prettiest way to do this but you might encounter this from someones script or so. This works for mean():

    > foo(1:10,mean)
    [1] 5.5
    

    But if I assign a new value to mean it breaks:

    mean <- 1
    foo(1:10,mean)
    
    Error in foo(1:10, mean) : could not find function "fun"
    

    This will happen very rarely, but it might happen. It is also very confusing for people if the same thing means two things:

    mean(mean)
    

    Since it is trivial to use any other name you want, why not use a different name then base R functions? Also, for some R variables this becomes even more important. Think of reassigning the '+' function! Another good example is reassignment of T and F which can break so much scripts.

提交回复
热议问题