r - 如何将两个小标题乘以列名
问题描述
我有两个具有相同列名的小标题:
待定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 中删除。
解决方案
我们可以使行tb1
和tb2
相等,然后将两个相等大小的数据帧相乘。
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"))
推荐阅读
- django - 模板不存在 django flatpages
- php - 如何更改数据库中数据的字体颜色以在 pdf 中打印,例如缺席 = 红色和当前 = 绿色?
- r - 计算模式在数据集中出现的次数
- python - Keras 中的分层 LSTM
- angular - 如何使用 Angular 将 JSON 存储在 QR 码中
- javascript - 如何在 hyperHTML 中动态更改标签
- postgresql - Mac 上的 PostgreSQL 设置
- angular - 如何存储 Angular 前端使用的 OAuth1 令牌
- ansible - 有什么方法可以在 Ansible 中为特定用户运行多个角色
- ios - Swift PDFKit:无法将视图缩放到小尺寸