0

I am having trouble using the special operator := (colon-equals) in a mapper function. I have found a workaround using a scoped-verb from the tidyverse but I would like to know in what way the special operator is implemented in a mapper function.

Basically I want to rename a set of variables with their associated attribute label respectively. I wrote the function for renaming one single variable but I cannot figure out how to write it in the same style using a scoped-verb variant or a mapper.

Here is my reproducible example:

I can rename one variable doing this:

library(tidyverse)
library(sjlabelled)
library(rlang) 

data(efc)

dat <- efc %>%
  rename(!!paste("c12hour", get_label(., c12hour), sep = "_") := c12hour)

# c12_hour becomes this:
names(dat[1])
[1] "c12hour_average number of hours of care per week"

I want to apply this function to the scoped verb rename_all which in my opinion would look like this but results in an error:

dat <- efc %>%
  rename_all(~!!paste(., get_label(.), sep = "_") := .)
Error: `:=` can only be used within a quasiquoted argument

This error also appears when I try to use a mapper:

geo_rename <- as_mapper(~rename(!!paste(., get_label(.), sep = "_") := .))

dat <- efc %>%
  map_dbl(., geo_rename)
Error: `:=` can only be used within a quasiquoted argument
Call `rlang::last_error()` to see a backtrace

I guess the problem lies in the usage of := operator which was invented for the quasiquotation problems that come up in the tidyeval framework. Am I using it wrong in the context of functional programming?

I have found a workaround by saving the labels which I want to paste on to in a named list:

dat <- efc

dat_labels <- get_label(dat)
dat_recode <- as.list(as.character(dat_labels))
names(dat_recode) <- get_label(dat)

dat <- efc %>%
  select_all(~paste(., dat_recode, sep = "_"))

But I would like to know how to use the := in Functional Programming. In Hadley Wickham's book it is shortly introduced but not used in a scoped verb or a mapper function https://adv-r.hadley.nz/quasiquotation.html#tidy-dots

Can someone explain this to me?

Thanks in advance!

mral
  • 118
  • 1
  • 8

1 Answers1

0

The scoped variants such as rename_all() do not use tidy eval. They are like the mappers in purrr, or lapply():

mtcars %>% rename_all(toupper)

Or with the formula notation for lambda functions:

mtcars %>% rename_all(~ toupper(.x))

Furthermore, in the case of rename_all(), the input to the mapped function is the column name, not the column vector which has the label attributes.

So I'm afraid you'll need to find a different solution. Both tidy eval and the scoped variants are outside of the solution space for this problem.

Lionel Henry
  • 6,652
  • 27
  • 33