How to multiply columns of a tibble by corresponding rows or columns of another tibble in R?

Viewed 136

I am trying to multiply columns of a tibble by rows of another tibble in R. I tried sweep and match from here but it only uses one vector (one column of the second tibble). A small sample of my first dataset looks like:

t_mode ch_value purpose sov ownership age_16 joint atwork sov_time
SHARED 2.06 eat 0 0 0 1 0 0.12
SHARED 2.19 eat 0 0 0 0 0 0.08
WALK 2.45 eat 0 1 0 1 0 0.02
PAY 2.30 eat 0 0 0 0 0 0.18
PAY 2.09 eat 0 0 0 0 0 0.12
ALONE 1.82 work 0 0 0 0 0 0.03
SHARED 0.2 work 0 0 0 1 0 0.14

and a small sample of the second dataset looks like:

Expression ALONE SHARED WALK PAY
sov -999 0 1 0
ownership -999 0 1 0
age_16 -999 0 1 0
joint -999 0 1 0
atwork 1 0 0 0
sov_time 1 0 0 0

The actual datasets are very large (1000 rows and 100k columns). I would appreciate it if anyone could help me find the solution.

1 Answers

One option could be:

df1 %>%
    rowwise() %>%
    mutate(across(all_of(df2$Expression), ~ . * df2[match(cur_column(), df2$Expression), match(t_mode, names(df2))]))

  t_mode ch_value purpose   sov ownership age_16 joint atwork sov_time
  <chr>     <dbl> <chr>   <int>     <int>  <int> <int>  <int>    <dbl>
1 SHARED     2.06 eat         0         0      0     0      0     0   
2 SHARED     2.19 eat         0         0      0     0      0     0   
3 WALK       2.45 eat         0         1      0     1      0     0   
4 PAY        2.3  eat         0         0      0     0      0     0   
5 PAY        2.09 eat         0         0      0     0      0     0   
6 ALONE      1.82 work        0         0      0     0      0     0.03
7 SHARED     0.2  work        0         0      0     0      0     0  
Related