Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Apply boxplot function within nests

I have a simple nest that groups by colour for iris then I want to apply a boxplot and grab the outliers from the dataset after it has been grouped.

For example:

bxplt <- function(DATA, X, Y){
  bxp <- boxplot(data = DATA, {{Y}}~{{X}}, outcex=2)
  cBXP <- bxp[4:5] %>% do.call(cbind.data.frame, bxp)
  return(xBXP)
}
upIris <- iris %>% mutate(colour = rep(c('Red', 'Blue', 'Green'), 50))
upIris %>% group_by(colour) %>% nest(.) %>% mutate(extra_data = map(data, ~ .x %>% bxplt(., Species, Sepal.Length)))

This gives the following error:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Error in mutate():
! Problem while computing extra_data = map(data, ~.x %>% bxplt(., Species, Sepal.Length)).
ℹ The error occurred in group 1: colour = "Blue".
Caused by error:
! object ‘Sepal.Length’ not found

>Solution :

You can use ensym() and inject() from rlang

library(rlang)
bxplt <- function(DATA, X, Y){
  y <- ensym(Y); x <- ensym(X)
  bxp <- inject(boxplot(!!y ~ !!x,data = DATA, outcex=2))
  do.call(cbind.data.frame, bxp[4:5])
}

Now, apply that function using map():

iris %>%
  mutate(colour = rep(c('Red', 'Blue', 'Green'), 50)) %>% 
  group_by(colour) %>% 
  nest() %>% 
  mutate(extra_data = map(data, ~bxplt(.x, Species, Sepal.Length)))

Output:

  colour data              extra_data  
  <chr>  <list>            <list>      
1 Red    <tibble [50 x 5]> <df [0 x 2]>
2 Blue   <tibble [50 x 5]> <df [8 x 2]>
3 Green  <tibble [50 x 5]> <df [1 x 2]>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading