Access lapply index names inside FUN

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

    Unfortunately, lapply only gives you the elements of the vector you pass it. The usual work-around is to pass it the names or indices of the vector instead of the vector itself.

    But note that you can always pass in extra arguments to the function, so the following works:

    x <- list(a=11,b=12,c=13) # Changed to list to address concerns in commments
    lapply(seq_along(x), function(y, n, i) { paste(n[[i]], y[[i]]) }, y=x, n=names(x))
    

    Here I use lapply over the indices of x, but also pass in x and the names of x. As you can see, the order of the function arguments can be anything - lapply will pass in the "element" (here the index) to the first argument not specified among the extra ones. In this case, I specify y and n, so there's only i left...

    Which produces the following:

    [[1]]
    [1] "a 11"
    
    [[2]]
    [1] "b 12"
    
    [[3]]
    [1] "c 13"
    

    UPDATE Simpler example, same result:

    lapply(seq_along(x), function(i) paste(names(x)[[i]], x[[i]]))
    

    Here the function uses "global" variable x and extracts the names in each call.

提交回复
热议问题