Access lapply index names inside FUN

前端 未结 12 2339
自闭症患者
自闭症患者 2020-11-22 15:04

Is there a way to get the list index name in my lapply() function?

n = names(mylist)
lapply(mylist, function(list.elem) { cat(\"What is the name of this list         


        
12条回答
  •  甜味超标
    2020-11-22 15:28

    Tommy's answer applies to named vectors but I got the idea you were interested in lists. And it seems as though he were doing an end-around because he was referencing "x" from the calling environment. This function uses only the parameters that were passed to the function and so makes no assumptions about the name of objects that were passed:

    x <- list(a=11,b=12,c=13)
    lapply(x, function(z) { attributes(deparse(substitute(z)))$names  } )
    #--------
    $a
    NULL
    
    $b
    NULL
    
    $c
    NULL
    #--------
     names( lapply(x, function(z) { attributes(deparse(substitute(z)))$names  } ))
    #[1] "a" "b" "c"
     what_is_my_name <- function(ZZZ) return(deparse(substitute(ZZZ)))
     what_is_my_name(X)
    #[1] "X"
    what_is_my_name(ZZZ=this)
    #[1] "this"
     exists("this")
    #[1] FALSE
    

提交回复
热议问题