In order to clean some of my datas, I have tried setting up an Excel VLOOKUP equivalent tu use with a dplyr::mutate() function :
vlookup <-
function(theString, theMapping)
{
library("magrittr")
which(
theMapping[1] == theString
)[1] %>%
theMapping[.,2]
}
Testing on a single string works fine :
test_mapping <-
tibble(
c("AD", "Andorra")
, c("AE", "United Arab Emirates")
, c("AF", "Afghanistan")
) %>%
t %>%
as_tibble
> "AD" %>% vlookup(test_mapping)
# A tibble: 1 x 1
V2
<chr>
1 Andorra
However, it doesn't work when applied on a tibble with mutate() :
tibble(
country = c("AE", "AF", "foo")
) %>%
mutate(
country_remap = country %>% vlookup(test_mapping)
)
> tibble(
+ country = c("AE", "AF", "foo")
+ ) %>%
+ mutate(
+ country_remap = country %>% vlookup(test_mapping)
+ )
# A tibble: 3 x 2
country country_remap$V2
<chr> <chr>
1 AE NA
2 AF NA
3 foo NA
Any idea to solve this?