[英]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 ![]() |
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 my 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).实际的数据集非常大(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.