Interesting tidy eval use cases

Last one from me, promise:

If you want to write a complex if_else statement, you can do it with map, quo and reduce. Eg.


library(tidyverse)

set.seed(123)

# define a plausible mapping. 
i = 1
numbers <- list()
pot <- seq(from = 1, to = (26*3), by = 1)
while (i <= 26) { 
	    numbers[[i]] <- sample(pot, 3)  
	    pot <- setdiff(pot, numbers %>% unlist)
	    i <- i + 1
	    }
 

mapping <- list(letters, numbers) %>%
		            transpose

# here's a tbl with only numbers
number_tbl <- tibble(number = sample(1:120, 10))

# this function creates the if_else statement for the mapping
build_ifelse <- function(mapping_list, col) { 
	 
	              col <- enquo(col)
	                 
	              mapping_list %>% map(~ list(quo(!!col %in% !!.[[2]]), .[[1]] ) ) %>%
                { c("other", .) } %>%
	              reduce(~ quo(if_else(!!(.y[[1]]), !!(.y[[2]]), !!.x )))           
	 
}

# use the function to create the expression
mapping_exp <- build_ifelse(mapping, number)

# use the expression in a mutate for create a new column from the mapping
number_tbl %>% mutate(letter = !!mapping_exp)
# # A tibble: 10 x 2
#    number letter
#     <int> <chr> 
#  1     43 x     
#  2     14 m     
#  3     29 l     
#  4     79 other 
#  5     49 k     
#  6     91 other 
#  7     12 o     
#  8     50 i     
#  9    111 other 
# 10    100 other

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.