你能用R中的apply实现'sweep'吗?

Rob*_*ace 2 r matrix apply

我正在刷我的R技能,最后觉得我已经掌握了奇怪的扫描功能,例如

df <- data.frame(a = 1:3, b = 2:4)
sweep(df, MARGIN = 2, STATS = c(5, 10), FUN = "*")

##    a  b
## 1  5 20
## 2 10 30
## 3 15 40
Run Code Online (Sandbox Code Playgroud)

并且更有效地在这里,在教程中,我正在实施中R的空间相互作用模型

他们说你明白的一个标志就是你可以用很多方式说出来,而且我认为这在编程中的应用比其他任何地方都要多.然而,尽管这个问题sweep解决了似乎仍然存在的问题,但apply我不知道他们是否在某种程度上可以互换.

那么,为了提高我对R的理解,有没有什么方法可以使用上述程序apply

Rei*_*son 7

This is close:

t(apply(df, 1, `*`, c(5,10)))
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

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().

  • @RobinLovelace效率; 尝试计时两种方法.`sweep`在一次调用中对所有元素应用`FUN`.`apply`在(在这种情况下)行上设置`for`循环并调用`FUN``nrow`次.但是`apply()`可以比`sweep()`做更多的事情,所以普遍性带来了价格. (2认同)