SongTianyang
SongTianyang

Reputation: 139

create a function providing the same result as lapply in R

I'm trying to analyze the efficiency of the lapply function in R, but I didn't find the original developing code of lapply in the folder "base", so I wrote a simple code by myself.

new_lapply<-function(data,f_name){
  list<-list()
  for (i in length(data)){
   list[i]<-f_name(data[,i])
  }
  return (list)
}
check<-Boston[1:10,]
lapply(check,length)

new_lapply(check,length)

Error: could not find function "f_name"

I wonder how to input a "general function name" in to a function, so I could run different functions in the new_lapply function, similar as the built-in lapply().

Thank you so much.

Upvotes: 2

Views: 95

Answers (1)

Rich Scriven
Rich Scriven

Reputation: 99331

You should use match.fun(). I've made a couple of other changes too. Hopefully this gets you in the right direction. Also, there's a good explanation of lapply() and its efficiency here

new_lapply <- function(data, f_name) {
    ## match the function in the 'f_name' argument
    f_name <- match.fun(f_name)
    ## allocate a list the same length as 'data' (ncol for data frames)
    List <- vector("list", length(data))
    for (i in seq_along(data)) {
        List[[i]] <- f_name(data[[i]])
    }
    ## if 'data' has names, carry them over to 'List' 
    if(!is.null(names(data))) 
        names(List) <- names(data)
    List
}

identical(lapply(mtcars, length), new_lapply(mtcars, length))
# [1] TRUE

um <- unname(mtcars)
identical(lapply(um, length), new_lapply(um, length))
# [1] TRUE

Upvotes: 1

Related Questions