R 中的广播

Jür*_*aak 8 arrays numpy r

(我来自Python,这就是为什么我的问题具有Python风格)

我有一个矩阵x( str(x)-> num[1:1000,1:4]) 和一个向量y( str(y) -> num[1:4])。我想从x中 coreespoonding 条目的每一列中减去y。IE x_y[i] = x[,i]-y[i]。

我发现这样做的方法是t(t(x)-y),但在我看来这是一种相当神秘的方法。有没有其他对读者更友好的方法来做到这一点?

对于那些了解 python 的人来说:我本质上是在寻找一种与 中已知的类似的广播方式,它可以通过等numpy来塑造维度。np.newaxis

cle*_*ens 3

还有其他选择。

我正在使用x和y创建这样的:

x <- matrix(1:4000, ncol = 4)

y <- 1:4
Run Code Online (Sandbox Code Playgroud)

第一个是使用sweep(),其中2是MARGIN:

sweep(x, 2, y)
Run Code Online (Sandbox Code Playgroud)

另一种方法是使用apply()循环遍历行x

apply(x, 2, function(xi, y) {

  xi - y

}, y = y)
Run Code Online (Sandbox Code Playgroud)

如果您查看评估您的选项的时间加上上述两个选项,您会发现您的选项是最快的。

microbenchmark::microbenchmark(
  t(t(x)-y), 
  apply(x, 2, function(xi, y) {

    xi - y

  }, y = y),
  sweep(x, 2, y),
  times = 1000
)
Run Code Online (Sandbox Code Playgroud)

输出:

Unit: microseconds
                                               expr    min      lq      mean  median      uq       max neval
                                        t(t(x) - y) 23.062 24.3390  32.30354 25.6270 27.2205  1044.485  1000
 apply(x, 2, function(xi, y) {     xi - y }, y = y) 67.541 70.6580  96.80288 75.1020 79.7865  1245.883  1000
                                     sweep(x, 2, y) 46.673 50.1955 108.42835 53.0515 57.0315 44158.248  1000
Run Code Online (Sandbox Code Playgroud)

由此您可能会得出这sweep()是性能和可读性之间的良好折衷,但t(t(x) - y)速度最快。