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!