How to use the 'sweep' function

前端 未结 5 2044
太阳男子
太阳男子 2020-12-02 05:18

When I look at the source of R Packages, i see the function sweep used quite often. Sometimes it\'s used when a simpler function would have sufficed (e.g.,

5条回答
  •  悲&欢浪女
    2020-12-02 05:29

    This question is a bit old, but since I've recently faced this problem a typical use of sweep can be found in the source code for the stats function cov.wt, used for computing weighted covariance matrices. I'm looking at the code in R 3.0.1. Here sweep is used to subtract out column means before computing the covariance. On line 19 of the code the centering vector is derived:

     center <- if (center) 
            colSums(wt * x)
        else 0
    

    and on line 54 it is swept out of the matrix

    x <- sqrt(wt) * sweep(x, 2, center, check.margin = FALSE)
    

    The author of the code is using the default value FUN = "-", which confused me for a while.

提交回复
热议问题