Access lapply index names inside FUN

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

    Just write your own custom lapply function

    lapply2 <- function(X, FUN){
      if( length(formals(FUN)) == 1 ){
        # No index passed - use normal lapply
        R = lapply(X, FUN)
      }else{
        # Index passed
        R = lapply(seq_along(X), FUN=function(i){
          FUN(X[[i]], i)
        })
      }
    
      # Set names
      names(R) = names(X)
      return(R)
    }
    

    Then use like this:

    lapply2(letters, function(x, i) paste(x, i))
    

提交回复
热议问题