您可以在 R 中使用 apply 实现“扫描"吗? [英] Can you implement 'sweep' using apply in R?

查看:33
本文介绍了您可以在 R 中使用 apply 实现“扫描"吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在复习我的 R 技能,终于感觉自己已经掌握了 奇怪的扫描功能 eg

I'm brushing up on my R skills and finally feel like I've mastered the strange sweep function e.g.

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

和更有用的这里,在我正在致力于实现空间交互模型的教程中R.

and more usefully here, on a tutorial I'm working on implementing a spatial interaction model in R.

他们说你理解某事的标志是你可以用多种方式表达,我认为这在编程中比在其他任何地方都更适用.然而,尽管 sweep 解决了看似 apply 式的问题,但我不知道它们是否在某种程度上可以互换.

They say that a sign you understand something is that you can say it in many ways, and I think this applies more in programming than almost anywhere else. Yet, despite the problem that sweep solves seeming apply-esque, I have NO IDEA whether they are to some degree interchangeable.

那么,为了提高我自己对R的理解,有没有什么办法可以用apply来做上面的过程?

So, in order to improve my own understanding of R, is there any way to do the above procedure using apply?

推荐答案

这就结束了:

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

行名丢失,但输出相同

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

为了分解这个,假设我们手动为 df 的第一行做这个,我们会写

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

这与使用参数 df[1, ]c(5, 10) 调用 '*'() 函数相同>

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

由此,我们有足够的东西来设置一个 apply() 调用:

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

  1. 我们按行工作,因此 MARGIN = 1,
  2. 我们应用函数 '*'() 所以 FUN = '*'
  3. 我们需要将第二个参数 c(5,10) 提供给 '*'(),我们通过 ... apply() 的参数.
  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().

唯一需要注意的是 apply() 如何将每次迭代"产生的向量粘在一起;这里它们是按列绑定的,因此我们需要转置 apply() 的结果,以便我们得到与 sweep() 相同的输出.

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

这篇关于您可以在 R 中使用 apply 实现“扫描"吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆