I couldn't find a question similar to the one that I have here. I have a very large named list of named vectors that match column names in a dataframe. I would like to use the list of named vectors to replace values in the dataframe columns that match each list element's name. That is, the name of the vector in the list matches the name of the dataframe column and the key-value pair in each vector element will be used to recode the column.
Reprex below:
library(tidyverse)
# Starting tibble
test <- tibble(Names = c("Alice","Bob","Cindy"),
A = c(3,"q",7),
B = c(1,2,"b"),
C = c("a","g",9))
# Named vector
A <- c("5" = "alpha", "7" = "bravo", "3" = "charlie", "q" = "delta")
B <- c("1" = "yes", "2" = "no", "b" = "bad", "c" = "missing")
C <- c("9" = "beta", "8" = "gamma", "a" = "delta", "g" = "epsilon")
# Named list of named vectors
dicts <- list("A" = A, "B" = B, "C" = C) # Same names as columns
I'm able to use mutate
and specify the column and list item manually.
# Works when replacement vector is specified
test %>%
mutate(across(c("A"),
~recode(., !!!dicts$A)))
#> # A tibble: 3 x 4
#> Names A B C
#> <chr> <chr> <chr> <chr>
#> 1 Alice charlie 1 a
#> 2 Bob delta 2 g
#> 3 Cindy bravo b 9
However, the following does not work:
# Does not work when replacement vector using column names
test %>%
mutate(across(c("A", "B", "C"),
~recode(., !!!dicts$.)))
Error: Problem with
mutate()
input..1
. x No replacements provided. i Input..1
is(function (.cols = everything(), .fns = NULL, ..., .names = NULL) ...
.
Additionally, I've found that map2_dfr
works only when all non-recoded columns are specified:
# map2_dfr Sort of works, but requires dropping some columns
map2_dfr(test %>% select(names(dicts)),
dicts,
~recode(.x, !!!.y))
#> # A tibble: 3 x 3
#> A B C
#> <chr> <chr> <chr>
#> 1 charlie yes delta
#> 2 delta no epsilon
#> 3 bravo bad beta
I'm looking to recode columns using the names from the list, without dropping columns.