Creating Label Column

When I am gathering the dataframe x, I lose the labels of the columns.
ie. I am trying to create a column with labels

library(tidyr)
library(WDI)
library(Hmisc)
x <- c("GE.EST", "RQ.EST") %>%
WDI::WDI(country = "all", indicator = .,
start = 2014, end = 2019, extra = FALSE)
Hmisc::label(x)
x <- x %>% gather("indicator", "value", -c(iso2c, country, year))

Not the most elegant (I'd love to drop the rementioning of x), but maybe it solves your problem.

x %>%
  pivot_longer(ends_with("EST"), names_to = "indicator") %>% 
  mutate(label = Hmisc::label(x)[indicator])

rorus, I like your solution, its elegant.
Here is a slightly longer alternative though, as it is a little more explicit, and lets the programmer 'interfere` with the labels easily also

library(tidyverse)
library(WDI)
library(Hmisc)
x <- c("GE.EST", "RQ.EST") %>%
  WDI::WDI(country = "all", indicator = .,
           start = 2014, end = 2019, extra = FALSE)

catchlabel <- enframe(x=Hmisc::label(x),
                      name = "indicator",
                      value= "label") 
x2 <- x %>%
  pivot_longer(ends_with("EST"), names_to = "indicator") %>% 
  left_join(catchlabel)

Thanks a lot for teaching me a new technique Hmisc::label(x)[indicator])

I have never thought that _join functions that can work without mention by in the code.

c("GE.EST", "RQ.EST") %>%
WDI::WDI(country = "all", indicator = .,
start = 2014, end = 2019) %>%
{left_join(pivot_longer(., -c(iso2c, country, year), "code"), # i used -c in case of having lot of variables.
Hmisc::label(.) %>% enframe("code", "indicator"))}
Thanks again for your help

If I may ask, what is this syntax with wrapping a pipe step with { } curly braces for ?

regards,

I think to pipe c("GE.EST", "RQ.EST") %>%
WDI::WDI(country = "all", indicator = .,
start = 2014, end = 2019) into pivot_longer and label.
Am I right?

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.