在R中创建成对产品矩阵

时间:2017-02-03 22:38:42

标签: r matrix

我需要采用以下数据框并使用prop变量的所有成对产品创建3x3矩阵。这是我开始的数据......

> example
  Parasite       prop
1  Hel_1.1 0.06818182
2   Hel_11 0.18181818
3   Hel_13 0.02272727

> dput(example)
structure(list(Parasite = structure(1:3, .Label = c("Hel_1.1", 
"Hel_11", "Hel_13", "Hel_14", "Hel_2", "Hel_3", "Hel_4", "Hel_4.5", 
"Hel_5", "Hel_6", "Hel_7", "Hel_9", "Pro_1", "Pro_2", "Hel_1.4"
), class = "factor"), prop = c(0.0681818181818182, 0.181818181818182, 
0.0227272727272727)), .Names = c("Parasite", "prop"), row.names = c(NA, 
3L), class = "data.frame")

我想获得一个看起来像这样的矩阵(成对产品值有点偏,因为我手工计算它们而没有均匀地舍入)

          Hel_1.1   Hel_11    Hel_13
Hel_1.1   .0046     .0122     .0015
Hel_11    .0122     .0324     .0039
Hel_13    .0015     .0039     .0004

我将不胜感激。

1 个答案:

答案 0 :(得分:2)

你可以试试这个:

prop <- example$prop
names(prop) <- example$Parasite
prop %o% prop
#            Hel_1.1      Hel_11       Hel_13
#Hel_1.1 0.004648760 0.012396694 0.0015495868
#Hel_11  0.012396694 0.033057851 0.0041322314
#Hel_13  0.001549587 0.004132231 0.0005165289