Reputation: 939
I'm trying to pivot this tibble with {tidyr} but withouT success...
Can someone help me ?
Many thanks in advance
library(tibble)
mydf <- tibble(
annee_methode=c("2016m2017","2017m2017"),
siren_ent=c("A","B"),
categorie_ent=c("PME","ETI"),
Prod=c(10,5),
Intens=c(2,3),
vaht=c(100,50),
effeqtp_ent=c(10,10),
immo_corp=c(20,30)
)
# Using this tibble to determine `Numerateur` and `Denominateur`
calcul_ratios <- tibble(
ratio = c("Prod","Intens"),
Numerateur = c("vaht","immo_corp"),
Denominateur = c("effeqtp_ent","effeqtp_ent")
)
# What I would like :
# A tibble: 2 x 7
Libelle Valeur_2016m2017 Numerateur_2016m2017 Denominateur_2016m2017 Valeur_2017m2017 Numerateur_2017m2017 Denominateur_2017m2017
<chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 Prod 10 100 10 5 50 10
2 Intens 2 20 10 3 30 10
Upvotes: 1
Views: 69
Reputation: 125208
You could do:
library(dplyr)
library(tidyr)
mydf %>%
select(-siren_ent, -categorie_ent) %>%
pivot_longer(-annee_methode) %>%
left_join(pivot_longer(calcul_ratios, everything()), by = c("name" = "value")) %>%
mutate(Libelle = rep(c("Prod","Intens"), 6),
name.y = ifelse(name.y == "ratio", "Valeur", name.y)) %>%
select(-name) %>%
pivot_wider(names_from = c(name.y, annee_methode), values_from = value)
#> # A tibble: 2 x 7
#> Libelle Valeur_2016m2017 Numerateur_2016m2… Denominateur_201… Valeur_2017m2017
#> <chr> <dbl> <dbl> <dbl> <dbl>
#> 1 Prod 10 100 10 5
#> 2 Intens 2 20 10 3
#> # … with 2 more variables: Numerateur_2017m2017 <dbl>,
#> # Denominateur_2017m2017 <dbl>
Upvotes: 2