Hello, people
I'm trying to use pmap.
I can write some simple map or map_df function.
I just want to use the mutate function in order to convert some variables to factor.
I have each variable's level/label stored.
This is how I do it step by step. As you will see, I'm coding 3 times the same verb and only changing the vector/list as input in mutate:
library(tidyverse)
set.seed(753963)
N <- 1000
enquete <- data.frame(
country = sample(1:4, size = N, replace = TRUE),
sex = sample(1:3, size = N, replace = TRUE),
code = sample(1:3, size = N, replace = TRUE))
enquete
country_lab<-c("Chad","Nigeria","Egypt","Senegal")
country_lev<-c(1:4)
sex_lab<-c("man","woman","no binary")
sex_lev<-c(1:3)
code_lab<-c("work","stud","ret")
code_lev<-c(1:3)
enquete %>%
mutate(
country=factor(country,country_lev,country_lab),
sex=factor(sex,sex_lev,sex_lab),
code=factor(code,code_lev,code_lab)
)
So, I thought using pmap because I have a list of 3 variables, a list of 3 variable's levels, and 3 variable's labels.
I am printing the first variable and his levels/labels just to ilustrate.
levels_<-list(country_lev,sex_lev,code_lev )
labels_<-list(country_lab,sex_lab,code_lab )
variables_<-c("country","sex","code")
variables_[1]
levels_[1]
labels_[1]
pmap(list(variables_,levels_,labels_),
.f=function(variables_, levels_, labels_)
{enquete %>% mutate(variables_=factor(variables_,levels =levels_,labels = labels_) ) }
)
When I run the pmap lines, I notice that no change is applied.
I think I am not too far away from the solution.
As always, thanks for your time and interest.
Have a nice weekend.