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

前端 未结 7 1276
孤独总比滥情好
孤独总比滥情好 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条回答
  •  旧时难觅i
    2020-11-29 15:16

    lapply applies a function over a list, do.call calls a function with a list of arguments. That looks like quite a difference to me...

    To give an example with a list :

    X <- list(1:3,4:6,7:9)
    

    With lapply you get the mean of every element in the list like this :

    > lapply(X,mean)
    [[1]]
    [1] 2
    
    [[2]]
    [1] 5
    
    [[3]]
    [1] 8
    

    do.call gives an error, as mean expects the argument "trim" to be 1.

    On the other hand, rbind binds all arguments rowwise. So to bind X rowwise, you do :

    > do.call(rbind,X)
         [,1] [,2] [,3]
    [1,]    1    2    3
    [2,]    4    5    6
    [3,]    7    8    9
    

    If you would use lapply, R would apply rbind to every element of the list, giving you this nonsense :

    > lapply(X,rbind)
    [[1]]
         [,1] [,2] [,3]
    [1,]    1    2    3
    
    [[2]]
         [,1] [,2] [,3]
    [1,]    4    5    6
    
    [[3]]
         [,1] [,2] [,3]
    [1,]    7    8    9
    

    To have something like Map, you need ?mapply, which is something different alltogether. TO get eg the mean of every element in X, but with a different trimming, you could use :

    > mapply(mean,X,trim=c(0,0.5,0.1))
    [1] 2 5 8
    

提交回复
热议问题