按元素乘以 tibbles

Multiply tibbles elementwise

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

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 包做到这一点?

像这样?

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