逐元素相乘

时间:2019-01-15 09:01:44

标签: r dplyr multiplication tibble elementwise-operations

我有两个小标题(行数和列数相等),如下所示:

first <- tibble::tribble(

~date,             ~col1,    ~col2,
"2000-01-01",       8.2,      10.10,
"2000-01-02",       3.2,      20.30,
"2000-01-03",       2.3,      10.3,
"2000-01-04",       5.5,      12.0,
"2000-01-05",       1.8,      10.7,
"2000-01-06",       1.3,      15.1,
"2000-01-07",       7.3,      16.2
)

second <- tibble::tribble(

~date,            ~col1,     ~col2,
"2000-01-01",        1,        0,
"2000-01-02",        1,        0,
"2000-01-03",        1,        0,
"2000-01-04",        1,        0,
"2000-01-05",        0,        0,
"2000-01-06",        0,        0,
"2000-01-07",        0,        1
)

我想将两个小节逐个元素相乘(当然不包括包含日期的第一列),得出以下结果:

result <- tibble::tribble(

~date,             ~col1,    ~col2,
"2000-01-01",       8.2,      0,
"2000-01-02",       3.2,      0,
"2000-01-03",       2.3,      0,
"2000-01-04",       5.5,      0,
"2000-01-05",        0,       0,
"2000-01-06",        0,       0,
"2000-01-07",        0,      16.2
)

使用dplyr软件包可以做到这一点吗?

1 个答案:

答案 0 :(得分:1)

喜欢吗?

first %>% keep(is.numeric) * second %>% keep(is.numeric)

  col1 col2
1  8.2  0.0
2  3.2  0.0
3  2.3  0.0
4  5.5  0.0
5  0.0  0.0
6  0.0  0.0
7  0.0 16.2

bind_cols(first %>% select(date),first %>% keep(is.numeric) * second %>% keep(is.numeric))

# A tibble: 7 x 3
  date        col1  col2
  <chr>      <dbl> <dbl>
1 2000-01-01   8.2   0  
2 2000-01-02   3.2   0  
3 2000-01-03   2.3   0  
4 2000-01-04   5.5   0  
5 2000-01-05   0     0  
6 2000-01-06   0     0  
7 2000-01-07   0    16.2