将R中的两个对象相乘

时间:2019-03-15 18:49:47

标签: r multiplying

有关将两个数字对象相乘的快速问题。 这是我的两个对象的样子。

P1 <- c(Low=.25,Medium=.50,High=.25)
P2 <- c(Low=.25,Medium=.50,High=.25)

我想要类似下面的内容。

P1       P2        P(P1*P2)
Low      Low       0.0625
Medium   Low       0.125
High     Low       0.0625
Low      Medium    0.125
Medium   Medium    0.250
High     Medium    0.125
Low      High      0.0625
Medium   High      0.125
High     High      0.0625

对此有何想法?

谢谢!

3 个答案:

答案 0 :(得分:4)

外部乘积由outer计算:

out <- outer(P1, P2)
dimnames(out) <- setNames(dimnames(out), c("P1", "P2"))        

    P2
P1          Low Medium   High
  Low    0.0625  0.125 0.0625
  Medium 0.1250  0.250 0.1250
  High   0.0625  0.125 0.0625

然后,您可以使用reshape2软件包将其放长格式:

reshape2::melt(out, value.name = "P(P1*P2)")

      P1     P2 P(P1*P2)
1    Low    Low   0.0625
2 Medium    Low   0.1250
3   High    Low   0.0625
4    Low Medium   0.1250
5 Medium Medium   0.2500
6   High Medium   0.1250
7    Low   High   0.0625
8 Medium   High   0.1250
9   High   High   0.0625

答案 1 :(得分:1)

我将tidyverseexpand.grid一起使用语法:

library(tidyverse)
P1 <- tribble(
  ~level, ~value1,
  "Low", 0.25,
  "Medium", 0.5,
  "High", 0.25
)
P2 <- tribble(
  ~level, ~value2,
  "Low", 0.25,
  "Medium", 0.5,
  "High", 0.25
)

expand.grid(p1_lev = P1$level, p2_lev = P2$level) %>% 
  left_join(P1, by = c("p1_lev" = "level")) %>% 
  left_join(P2, by = c("p2_lev" = "level")) %>% 
  mutate(new_value = value1*value2) %>% 
  select(-value1, -value2)


答案 2 :(得分:1)

另一种,与上面类似:

library(tidyverse)

expand.grid(names(P1), names(P2)) %>%
  mutate(Var3 = P1[Var1] * P2[Var2]) %>%
  rename(Var1 = "P1", Var2 = "P2", Var3 = "P(P1 * P2)")

      P1     P2 P(P1 * P2)
1    Low    Low     0.0625
2 Medium    Low     0.1250
3   High    Low     0.0625
4    Low Medium     0.1250
5 Medium Medium     0.2500
6   High Medium     0.1250
7    Low   High     0.0625
8 Medium   High     0.1250
9   High   High     0.0625