In R, how to get an object's name after it is sent to a function?

前端 未结 3 613
傲寒
傲寒 2020-11-22 09:37

I am looking for the reverse of get().

Given an object name, I wish to have the character string representing that object extracted directly from the ob

3条回答
  •  一生所求
    2020-11-22 10:38

    The old deparse-substitute trick:

    a<-data.frame(x=1:10,y=1:10)
    test<-function(z){
       mean.x<-mean(z$x)
       nm <-deparse(substitute(z))
       print(nm)
       return(mean.x)}
    
     test(a)
    #[1] "a"   ... this is the side-effect of the print() call
    #          ... you could have done something useful with that character value
    #[1] 5.5   ... this is the result of the function call
    

    Edit: Ran it with the new test-object

    Note: this will not succeed inside a local function when a set of list items are passed from the first argument to lapply (and it also fails when an object is passed from a list given to a for-loop.) You would be able to extract the ".Names"-attribute and the order of processing from the structure result, if it were a named vector that were being processed.

    > lapply( list(a=4,b=5), function(x) {nm <- deparse(substitute(x)); strsplit(nm, '\\[')} )
    $a
    $a[[1]]
    [1] "X"    ""     "1L]]"
    
    
    $b
    $b[[1]]
    [1] "X"    ""     "2L]]"
    
    > lapply( c(a=4,b=5), function(x) {nm <- deparse(substitute(x)); strsplit(nm, '\\[')} )
    $a
    $a[[1]]
    [1] "structure(c(4, 5), .Names = c(\"a\", \"b\"))" ""                                            
    [3] "1L]]"                                        
    
    
    $b
    $b[[1]]
    [1] "structure(c(4, 5), .Names = c(\"a\", \"b\"))" ""                                            
    [3] "2L]]"  
    

提交回复
热议问题