Access lapply index names inside FUN

前端 未结 12 2292
自闭症患者
自闭症患者 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:38

    This basically uses the same workaround as Tommy, but with Map(), there's no need to access global variables which store the names of list components.

    > x <- list(a=11, b=12, c=13)
    > Map(function(x, i) paste(i, x), x, names(x))
    $a
    [1] "a 11"
    
    $b
    [1] "b 12"
    
    $c
    [1] "c 13
    

    Or, if you prefer mapply()

    > mapply(function(x, i) paste(i, x), x, names(x))
         a      b      c 
    "a 11" "b 12" "c 13"
    

提交回复
热议问题