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

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

问题描述

我正在复习我的R技能,最终感觉就像我已经掌握了

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

更有用的是在此,我正在研究一个教程,其中实现了空间交互模型

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

行名会丢失,但是输出是相同的

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

要对此进行细分,请说我们是在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)

> '*'(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天全站免登陆