I need to face below data procesing related problem. How to reshape data given dataframe into demand output?
given df:
pln <- tibble(code = c("PLN","EUR","USD"),
value_in_PLN = c(1,4.6,4.3))
Demand output:
pln_matrix <- tibble(code = c("PLN","USD","EUR"),
PLN = c(1,4.3,4.6),
USD = c(1/4.3, 1, 4.3/4.6),
EUR = c(1/4.6, 4.6/4.3,1))
Thnaks in advance for any hint! Additionally, it would be the best way if it is possible to use tidyverse functionality to deal with that.
CodePudding user response:
a <- pln$value_in_PLN %*% t(1/pln$value_in_PLN)
colnames(a) <- pln$code
cbind(pln, a)
code value_in_PLN PLN EUR USD
1 PLN 1.0 1.0 0.2173913 0.2325581
2 EUR 4.6 4.6 1.0000000 1.0697674
3 USD 4.3 4.3 0.9347826 1.0000000
a
can also be computed as
outer(pln$value_in_PLN, pln$value_in_PLN, '/')
[,1] [,2] [,3]
[1,] 1.0 0.2173913 0.2325581
[2,] 4.6 1.0000000 1.0697674
[3,] 4.3 0.9347826 1.0000000
or even:
tcrossprod(pln$value_in_PLN, 1/pln$value_in_PLN)
[,1] [,2] [,3]
[1,] 1.0 0.2173913 0.2325581
[2,] 4.6 1.0000000 1.0697674
[3,] 4.3 0.9347826 1.0000000
CodePudding user response:
library(tidyverse)
pln <- tibble(code = c("PLN","EUR","USD"),
PLN = c(1,4.6,4.3))
bind_cols(code = pln$code,
map2_dfc(
.x = pln$code,
.y = pln$PLN,
.f = ~ transmute(pln,!!.x := pln$PLN / .y)
))
#> # A tibble: 3 × 4
#> code PLN EUR USD
#> <chr> <dbl> <dbl> <dbl>
#> 1 PLN 1 0.217 0.233
#> 2 EUR 4.6 1 1.07
#> 3 USD 4.3 0.935 1
Created on 2022-04-26 by the reprex package (v2.0.1)