Why is using assign bad?

后端 未结 3 1698
悲&欢浪女
悲&欢浪女 2020-11-21 23:56

This post (Lazy evaluation in R – is assign affected?) covers some common ground but I am not sure it answers my question.

I stopped using assign when I

3条回答
  •  星月不相逢
    2020-11-22 00:03

    As the source of fortune(236) I thought I would add a couple examples (also see fortune(174)).

    First, a quiz. Consider the following code:

    x <- 1
    y <- some.function.that.uses.assign(rnorm(100))
    

    After running the above 2 lines of code, what is the value of x?

    The assign function is used to commit "Action at a distance" (see http://en.wikipedia.org/wiki/Action_at_a_distance_(computer_programming) or google for it). This is often the source of hard to find bugs.

    I think the biggest problem with assign is that it tends to lead people down paths of thinking that take them away from better options. A simple example is the 2 sets of code in the question. The lapply solution is more elegant and should be promoted, but the mere fact that people learn about the assign function leads people to the loop option. Then they decide that they need to do the same operation on each object created in the loop (which would be just another simple lapply or sapply if the elegant solution were used) and resort to an even more complicated loop involving both get and apply along with ugly calls to paste. Then those enamored with assign try to do something like:

    curname <- paste('myvector[', i, ']')
    assign(curname, i)
    

    And that does not do quite what they expected which leads to either complaining about R (which is as fair as complaining that my next door neighbor's house is too far away because I chose to walk the long way around the block) or even worse, delve into using eval and parse to get their constructed string to "work" (which then leads to fortune(106) and fortune(181)).

提交回复
热议问题