简体   繁体   English

如何将 tibble 的列乘以 R 中另一个 tibble 的相应行或列?

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

I am trying to multiply columns of a tibble by the rows of another tibble in R.我正在尝试将 tibble 的列乘以 R 中另一个 tibble 的行。 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 t_mode ch_value ch_value purpose目的 sov索夫 ownership所有权 age_16年龄_16 joint联合的 atwork在工作 sov_time sov_time
SHARED共享 2.06 2.06 eat 0 0 0 0 0 0 1 1 0 0 0.12 0.12
SHARED共享 2.19 2.19 eat 0 0 0 0 0 0 0 0 0 0 0.08 0.08
WALK 2.45 2.45 eat 0 0 1 1 0 0 1 1 0 0 0.02 0.02
PAY支付 2.30 2.30 eat 0 0 0 0 0 0 0 0 0 0 0.18 0.18
PAY支付 2.09 2.09 eat 0 0 0 0 0 0 0 0 0 0 0.12 0.12
ALONE独自的 1.82 1.82 work工作 0 0 0 0 0 0 0 0 0 0 0.03 0.03
SHARED共享 0.2 0.2 work工作 0 0 0 0 0 0 1 1 0 0 0.14 0.14

and my a small sample of the second dataset looks like:我的第二个数据集的一个小样本看起来像:

Expression表达 ALONE独自的 SHARED共享 WALK PAY支付
sov索夫 -999 -999 0 0 1 1 0 0
ownership所有权 -999 -999 0 0 1 1 0 0
age_16年龄_16 -999 -999 0 0 1 1 0 0
joint联合的 -999 -999 0 0 1 1 0 0
atwork在工作 1 1 0 0 0 0 0 0
sov_time sov_time 1 1 0 0 0 0 0 0

The actual datasets are very large (1000 rows and 100k columns).实际的数据集非常大(1000 行和 100k 列)。 I would appreciate it if anyone could help me find the solution.如果有人可以帮助我找到解决方案,我将不胜感激。

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  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM