首页 > 解决方案 > 如何将两个小标题乘以列名

问题描述

我有两个具有相同列名的小标题:

待定1:

   date        a     b     c     d     e
  <date>     <dbl> <dbl> <dbl> <dbl> <dbl>
1 2017-06-01  113.  182.  21.0  31.9  111.

待定2:

   date        a     b     c     d     e
  <date>     <dbl> <dbl> <dbl> <dbl> <dbl>
1 2016-05-01  122. 106.   23.9  43.7  93.5
2 2016-06-01  117. 111.   20.8  41.6  111. 
3 2016-07-01  116.  94.4  22.5  41.0  92.4

我想将 tb2 的每一行乘以 tb1 中的相应数字,有没有一种简单的方法可以用 dplyr 或其他方式做到这一点?我需要保留 tb2 中的日期,但我已将其从 tb1 中删除。

标签: rdplyrtibble

解决方案


我们可以使行tb1tb2相等,然后将两个相等大小的数据帧相乘。

cbind(tb2[1], tb1[rep(1, nrow(tb2)), -1] * tb2[-1])

#       date     a       b     c       d       e
#1 2016-05-01 13786 19292.0 501.9 1394.03 10378.5
#2 2016-06-01 13221 20202.0 436.8 1327.04 12321.0
#3 2016-07-01 13108 17180.8 472.5 1307.90 10256.4

tb1如果和中的列tb2顺序不同,我们可以先做

tb1 <- tb1[match(names(tb2), names(tb1))]

然后使用上面的。

数据

tb1 <- structure(list(date = structure(1L, .Label = "2017-06-01", class = "factor"),
a = 113, b = 182, c = 21, d = 31.9, e = 111), class = "data.frame", row.names = "1")

tb2 <- structure(list(date = structure(1:3, .Label = c("2016-05-01", 
"2016-06-01", "2016-07-01"), class = "factor"), a = c(122, 117, 
116), b = c(106, 111, 94.4), c = c(23.9, 20.8, 22.5), d = c(43.7, 
41.6, 41), e = c(93.5, 111, 92.4)), class = "data.frame", 
row.names = c("1", "2", "3"))

推荐阅读