How to use the 'sweep' function

前端 未结 5 2052
太阳男子
太阳男子 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:28

    sweep() is typically used when you operate a matrix by row or by column, and the other input of the operation is a different value for each row / column. Whether you operate by row or column is defined by MARGIN, as for apply(). The values used for what I called "the other input" is defined by STATS. So, for each row (or column), you will take a value from STATS and use in the operation defined by FUN.

    For instance, if you want to add 1 to the 1st row, 2 to the 2nd, etc. of the matrix you defined, you will do:

    sweep (M, 1, c(1: 4), "+")
    

    I frankly did not understand the definition in the R documentation either, I just learned by looking up examples.

提交回复
热议问题