Search code examples
rpivot-tabledivision

Turn vector into division table R


I have 2 columns, one is Country and the other is Value

How can I make turn this table into a division table of sorts such that each value is divided by every other value and I would have the Country as rownames and column names, the values would be every possible division value. The picture describes what I'm trying to accomplish but in Excel. I would like to do this in R. Where the first table in transformed into the second table. I don't care to have the original values displayed in yellow only the division table.

Transform top table into bottom table

I've tired many combinations of pivoting, joining, copying columns etc and get close but not the result I'm looking for. Is there a tidy way to do this?


Solution

  • You're looking for outer:

    x <- c(Argentina = 1.7, Australia = 5.5, Belgium = 0.5, Brazil = 8.7)
    t(outer(x, x, `/`))
    

    output

              Argentina  Australia    Belgium    Brazil
    Argentina 1.0000000  3.2352941 0.29411765  5.117647
    Australia 0.3090909  1.0000000 0.09090909  1.581818
    Belgium   3.4000000 11.0000000 1.00000000 17.400000
    Brazil    0.1954023  0.6321839 0.05747126  1.000000