Matthew Loop Matthew Loop - 1 month ago 6
R Question

How do I create a variable with mutate() that has values equal to the label of a given variable?

I am trying to use

mutate()
on a
data.frame
that I have used
gather()
on to create a variable whose values are the
label()
for the gathered
variable
. I have searched Google and StackOverflow and have not found a suitable answer. My research led me to think that standard evaluation might be needed.

Here is a minimal reproducible example:

# Packages
library(dplyr)
library(Hmisc)
library(tidyr)
library(lazyeval)

df <- mtcars %>%
tbl_df() %>%
slice(1)

label(df$mpg) <- "Miles per gallon"
label(df$cyl) <- "Cylinders"

df %>%
select(mpg, cyl) %>%
gather(variable, value) %>%
mutate_(.dots = interp(~attr(df$x, "label"), x = variable))


This code produces:

# A tibble: 2 × 3
variable value `attr(df$mpg, "label")`
<chr> <dbl> <chr>
1 mpg 21 Miles per gallon
2 cyl 6 Miles per gallon


which is clearly only getting the label for
mpg
.

My goal is to have something like:

# A tibble: 2 × 3
variable value `attr(df$variable, "label")`
<chr> <dbl> <chr>
1 mpg 21 Miles per gallon
2 cyl 6 Cylinders

Answer

what about this?

df %>% 
    select(mpg, cyl) %>%
    gather(variable, value) %>% 
    mutate(labels = label(df)[variable])

# A tibble: 2 × 3
  variable value           labels
     <chr> <dbl>            <chr>
1      mpg    21 Miles per gallon
2      cyl     6        Cylinders