将同一数据表中的几组列相乘 [英] Multiply several sets of columns in the same data.table

查看:102
本文介绍了将同一数据表中的几组列相乘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种将 data.table 的几列乘以同一DT中其他几列的方法。另一篇文章重点介绍了在同一DT中用 specific 列乘以许多列的方式将R中的其他特定列乘以data.table吗?。我的问题扩大了先前的问题。

I am looking for a way to multiply several columns of a data.table by several other columns in the same DT. Another post focused on the way to multiply many columns by a specific column in the same DT Multiply many columns by a specific other column in R with data.table?. My question broadens this prior question.

从此DT开始:

DT <- data.table(x1 = 1:5L, y1 = 6:10L, x2 = 11:15L, y2 = 16:20L)

   x1 y1 x2 y2
1:  1  6 11 16
2:  2  7 12 17
3:  3  8 13 18
4:  4  9 14 19
5:  5 10 15 20

我想乘以 z1 = x1 * y1 z2 = x2 * y2 以获得

   x1 y1 x2 y2 z1  z2
1:  1  6 11 16  6 176
2:  2  7 12 17 14 204
3:  3  8 13 18 24 234
4:  4  9 14 19 36 266
5:  5 10 15 20 50 300

以下是构建所需DT的蛮力方式:

Here is a brute force way of building the desired DT:

DT2[, ':='(z1 = x1 * y1, z2 = x2 * y2]

当然,必须有一个优雅的

Certainly there must be an elegant way to do this.

推荐答案

可能是个口味问题,但是您可以使用 Map 并构建一些列表来填充它。

Probably a matter of taste, but you could use Map and build some lists to feed it.

DT[, c("z1", "z2") := Map("*", list(x1, x2), list(y1, y2))]

扩展到许多变量与 mget ls 结合,做

Expanding to many variables combine with mget and ls, do

DT[, c("z1", "z2") := Map("*", mget(ls(pattern="x")), mget(ls(pattern="y")))]

这两个都返回期望的结果

Both of these return the desired result

DT
   x1 y1 x2 y2 z1  z2
1:  1  6 11 16  6 176
2:  2  7 12 17 14 204
3:  3  8 13 18 24 234
4:  4  9 14 19 36 266
5:  5 10 15 20 50 300

我只提到 mget ls 模式可用于返回特定环境中存在的对象的列表。 ls 默认情况下搜索父环境,该父环境是在其中调用data.table的环境。因此,如果您有一个名为x3的对象存在于data.table之外,则不必担心:该对象将被忽略。

I'll just mention that mget and ls with patterns can be used to return lists of objects that exist in a particular environment. ls searches the parent environment by default, which is the environment of the data.table in which it was called. So in the instance that you have an object named x3 that exists outside of the data.table, you needn't worry: that object is ignored.

这篇关于将同一数据表中的几组列相乘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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