I want to recode a bunch of variables with as few function calls as possible. I have one data.frame where I want to recode a number of variables. I create a named list of all variable names and the recoding arguments I want to execute. Here I have no problem using map
and dpylr
. However, when it comes to recoding I find it much easier using recode
from the car
package, instead of dpylr
's own recoding function. A side question is whether there is a nice way of doing the same thing with dplyr::recode
.
As a next step I break the data.frame down into a nested tibble. Here I want to do specific recodings in each subset. This is where things get complicated and I am not able to do this in a dpylr
pipe anymore. The only thing I get working is a very ugly nested for loop
.
Looking for ideas to do this in a nice and clean way.
Lets start with the easy example:
library(carData)
library(dplyr)
library(purrr)
library(tidyr)
# global recode list
recode_ls = list(
mar = "'not married' = 0;
'married' = 1",
wexp = "'no' = 0;
'yes' = 1"
)
recode_vars <- names(Rossi)[names(Rossi) %in% names(recode_ls)]
Rossi2 <- Rossi # lets save results under a different name
Rossi2[,recode_vars] <- recode_vars %>% map(~ car::recode(Rossi[[.x]],
recode_ls[.x],
as.factor = FALSE,
as.numeric = TRUE))
So far this seems pretty clean to me, apart from the fact that car::recode is much easier to use than dplyr::recode.
Here comes my actual problem. What I am trying to do is recode (in this easy example) the variables mar
and wexp
differently in each tibble subset. In my real data set the variables I want to recode in each subset are many more and have different names too. Does anyone have a good idea how to do this nice and clean using a dpylr
pipe and map
?
nested_rossi <- as_tibble(Rossi) %>% nest(-race)
recode_wexp_ls = list(
no = list(
mar = "'not married' = 0;
'married' = 1",
wexp = "'no' = 0;
'yes' = 1"
),
yes = list(
mar = "'not married' = 1;
'married' = 2",
wexp = "'no' = 1;
'yes' = 2"
)
We could also attach the list to the nested data.frame, but I'm not sure if this would make things more efficient.
nested_rossi$recode = list(
no = list(
mar = "'not married' = 0;
'married' = 1",
wexp = "'no' = 0;
'yes' = 1"
),
yes = list(
mar = "'not married' = 1;
'married' = 2",
wexp = "'no' = 1;
'yes' = 2"
)
)