Search code examples
rdplyrmultiplicationtibbleelementwise-operations

Multiply tibbles elementwise


I have two tibbles (equal number of rows and columns) like this:

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
)

I would like to multiply both tibbles elementwise (excluding the first column containing the dates, of course), yielding the following result:

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
)

Is there any possibilty to do this using the dplyr package?


Solution

  • Like this?

    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
    

    or

    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