Can you implement 'sweep' using apply in R?

人走茶凉 提交于 2019-12-06 07:30:36

This is close:

t(apply(df, 1, `*`, c(5,10)))

The row names are lost but otherwise the output is the same

> t(apply(df, 1, '*', c(5,10)))
      a  b
[1,]  5 20
[2,] 10 30
[3,] 15 40

To break this down, say we were doing this by hand for the first row of df, we'd write

> df[1, ] * c(5, 10)
  a  b
1 5 20

which is the same as calling the '*'() function with arguments df[1, ] and c(5, 10)

> '*'(df[1, ], c(5, 10))
  a  b
1 5 20

From this, we have enough to set up an apply() call:

  1. we work by rows, hence MARGIN = 1,
  2. we apply the function '*'() so FUN = '*'
  3. we need to supply the second argument, c(5,10), to '*'(), which we do via the ... argument of apply().

The only extra thing to realise is how apply() sticks together the vector resulting from each "iteration"; here they are bound column-wise and hence we need to transpose the result from apply() so that we get the same output as sweep().

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!