Getting a function name as a string

后端 未结 8 1280
半阙折子戏
半阙折子戏 2020-12-01 03:18

Say I have a bunch of functions, each with something likeMyFunction.1, etc. I want to pass these functions into another function, which prints out a small repo

8条回答
  •  伪装坚强ぢ
    2020-12-01 03:52

    When a function is passed around as an object, it loses its name. See, for example, the results of the following lines:

    str(lm)
    lm
    

    You can get the arguments and the body of the function, but not the name.

    My suggestion would be to construct a named list of functions, where the name could be printed:

    > somefns <- list(lm=lm, aggregate=aggregate)
    > str(somefns)
    List of 2
     $ lm       :function (formula, data, subset, weights, na.action, method = "qr", 
        model = TRUE, x = FALSE, y = FALSE, qr = TRUE, singular.ok = TRUE, 
        contrasts = NULL, offset, ...)  
     $ aggregate:function (x, ...) 
    
    > somefns[[1]](dist ~ speed, data=cars)
    
    Call:
    somefns[[1]](formula = dist ~ speed, data = cars)
    
    Coefficients:
    (Intercept)        speed  
         -17.58         3.93  
    
    > names(somefns)[[1]]
    [1] "lm"
    

提交回复
热议问题