What's the difference between lapply and do.call?

前端 未结 7 1286
孤独总比滥情好
孤独总比滥情好 2020-11-29 14:46

I\'m learning R recently and confused by two function: lapplyand do.call. It seems that they\'re just similar to map function in Lisp.

7条回答
  •  孤街浪徒
    2020-11-29 15:02

    Although there have been many answers, here is my example for reference. Suppose we have a list of data as :

    L=list(c(1,2,3), c(4,5,6))
    

    The function lapply returns a list.

    lapply(L, sum) 
    

    The above means something like below.

    list( sum( L[[1]]) , sum( L[[2]]))
    

    Now let us do the same thing for do.call

    do.call(sum, L) 
    

    It means

    sum( L[[1]], L[[2]])
    

    In our example, it returns 21. In short, lapply always returns a list while the return type of do.call really depends on the function executed.

提交回复
热议问题