简体   繁体   English

将 dataframe 中的列乘以另一个 dataframe 中给出的值

[英]Multiply columns in dataframe by values given in another dataframe

I've been trying to accomplish this in dplyr but not been able to figure it out.我一直在尝试在 dplyr 中完成此操作,但无法弄清楚。

In one data frame (df1) I have columns with values.在一个数据框 (df1) 中,我有包含值的列。

|A  |B  |
|23 |43 |
|24 |11 |

In another data frame (df2) I have valus.在另一个数据框 (df2) 中,我有 valus。

|Column|Value|
|A     |0.12 |
|B     |1.23 |

I want to somehow multiple every cell in column 'A' of df1 by the given value in df2 for that column.我想以某种方式将 df1 的“A”列中的每个单元格乘以 df2 中该列的给定值。 Seems like it should be trivial but I've not quite figured out the correct syntax.看起来应该是微不足道的,但我还没有完全弄清楚正确的语法。 I suspect I was use mutate, but any advice would be appreciated.我怀疑我使用的是 mutate,但如有任何建议,我们将不胜感激。

Mostly trying to accomplish this in dplyr but welcome to other suggestions.主要是尝试在 dplyr 中完成此操作,但欢迎提出其他建议。

You can use mutate(across()) , and leverage cur_column() to subset the second data frame您可以使用mutate(across()) ,并利用cur_column()对第二个数据框进行子集化

mutate(d1, across(A:B, ~.x*d2[d2$Column==cur_column(),2]))

Output Output

      A     B
  <dbl> <dbl>
1  2.76  52.9
2  2.88  13.5

Input:输入:

d1 = data.frame(A = c(23,24), B=c(43,11))
d2 = data.frame(Column = c("A","B"), Value = c(.12,1.23))

This can be extended to any number of columns;这可以扩展到任意数量的列; here is an input with three columns, A,B,C.这是一个包含三列的输入,A、B、C。

d1 = data.frame(A = c(23,24), B=c(43,11), C=c(25,16))
d2 = data.frame(Column = c("A","B", "C"), Value = c(.12,1.23, 0.75))

mutate(d1, across(where(is.numeric), ~.x*d2[d2$Column==cur_column(),2]))


     A     B     C
1 2.76 52.89 18.75
2 2.88 13.53 12.00

There is a much more verbose approach where d1 is pivoted longer and joined to d2, the calculation done, and the result pivoted_wider.有一种更冗长的方法,其中 d1 旋转更长并连接到 d2,计算完成,结果 pivoted_wider。 It provides the same output:它提供相同的 output:

inner_join(d2, pivot_longer(d1,everything(), names_to = "Column", values_to = "value")) %>% 
  mutate(value = Value*value) %>%
  select(-Value) %>% 
  pivot_wider(names_from=Column, values_from = value, values_fn=list) %>% 
  unnest(everything())

Output: Output:

      A     B     C
  <dbl> <dbl> <dbl>
1  2.76  52.9  18.8
2  2.88  13.5  12  

Multiplies values in d1 column A with value in d2 where Column is A:将 d1 列 A 中的值乘以 d2 中的值,其中列为 A:

library(dplyr)

d1 %>% 
  mutate(A = A * d2$Value[d2$Column=="A"])
     A  B
1 2.76 43
2 2.88 11

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

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