How do I access the name of the variable assigned to the result of a function within the function?

后端 未结 4 1387
感情败类
感情败类 2020-12-09 21:58

For example, suppose I would like to be able to define a function that returned the name of the assignment variable concatenated with the first argument:

a &         


        
4条回答
  •  长情又很酷
    2020-12-09 22:47

    This is generally not possible because the operator <- is actually parsed to a call of the <- function:

    rapply(as.list(quote(a <- add_str("b"))), 
           function(x) if (!is.symbol(x)) as.list(x) else x,
           how = "list")
    #[[1]]
    #`<-`
    #
    #[[2]]
    #a
    #
    #[[3]]
    #[[3]][[1]]
    #add_str
    #
    #[[3]][[2]]
    #[1] "b"
    

    Now, you can access earlier calls on the call stack by passing negative numbers to sys.call, e.g.,

     foo <- function() {
      inner <- sys.call()
      outer <- sys.call(-1)
      list(inner, outer)
    }
    
    print(foo())
    #[[1]]
    #foo()
    #[[2]]
    #print(foo())
    

    However, help("sys.call") says this (emphasis mine):

    Strictly, sys.parent and parent.frame refer to the context of the parent interpreted function. So internal functions (which may or may not set contexts and so may or may not appear on the call stack) may not be counted, and S3 methods can also do surprising things.

    <- is such an "internal function":

    `<-`
    #.Primitive("<-")
    
    `<-`(x, foo())
    x
    #[[1]]
    #foo()
    #
    #[[2]]
    #NULL
    

提交回复
热议问题