Home > database >  Turn vector into division table R
Turn vector into division table R

Time:11-28

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?

CodePudding user response:

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

CodePudding user response:

x = c(arg = 1.7, aus = 5.5, bel = 0.5, bra = 8.7)

y = outer(x, x, FUN = \(a,b) b/a)
y

#           arg        aus        bel       bra
# arg 1.0000000  3.2352941 0.29411765  5.117647
# aus 0.3090909  1.0000000 0.09090909  1.581818
# bel 3.4000000 11.0000000 1.00000000 17.400000
# bra 0.1954023  0.6321839 0.05747126  1.000000

cbind(c(NA, x), rbind(" " = x, y))

#               arg        aus        bel       bra
#      NA 1.7000000  5.5000000 0.50000000  8.700000
# arg 1.7 1.0000000  3.2352941 0.29411765  5.117647
# aus 5.5 0.3090909  1.0000000 0.09090909  1.581818
# bel 0.5 3.4000000 11.0000000 1.00000000 17.400000
# bra 8.7 0.1954023  0.6321839 0.05747126  1.000000
  • Related