【发布时间】:2018-08-14 22:25:32
【问题描述】:
如何有效地将行数相同但列数不同的两个不同数据帧的列相乘。
我有两个数据集成交量和价格,我想将每个成交量列乘以每个价格列,这样生成的数据框将有 nXm 列(n 在第一个数据帧中是 ncols,m 在第二个数据帧中是 ncols )。
set.seed(159) # for reproducibility
volumes <- as.data.frame(cbind(Year = 2000:2004,
matrix(round(runif(25, 50, 100), 0),
nrow = 5, ncol = 5)))
names(volumes) <- c("Year", paste(rep("V", 5), seq(1:5), sep = ""))
volumes
Year V1 V2 V3 V4 V5
1 2000 56 52 88 81 52
2 2001 81 56 90 76 69
3 2002 81 92 69 93 69
4 2003 56 68 77 80 72
5 2004 51 58 62 53 62
set.seed(159)
prices <- as.data.frame(cbind(Year = 2000:2004,
matrix(round(runif(20, 5, 15), 0),
nrow = 5, ncol = 2)))
names(prices) <- c("Year", paste(rep("P", 2), seq(1:2), sep = ""))
prices
Year P1 P2
1 2000 6 5
2 2001 11 6
3 2002 11 13
4 2003 6 9
5 2004 5 7
【问题讨论】:
-
Year的值是否总是相同的?也就是说,我们可以将一列乘以另一列,还是需要先将行匹配Year? -
对于我当前的问题,我有相同的问题,但最好知道如何匹配然后相乘,以防它们不一样。
标签: r