0

He llegado por fin a una función para plotear mis outliers por una variable id, pero me falla estrepitosamente al encontrar un missing Value.

He intentado variar la función is_outlier para que acepte Na's pero el problema fundamental es el del mutate, el cual no consigo ponerle el argumento que me está dando como fallo.

Error: Problem with mutate() input is_outlier. x missing values and NaN's not allowed if 'na.rm' is FALSE i Input is_outlier is ifelse(is_outlier(disp), disp, as.numeric(NA)). i The error occurred in group 3: cyl = 8. Run rlang::last_error() to see where the error occurred.

Aquí dejo el código con mtcars como ejemplo.

library(dplyr)
library(ggplot2)
library(tibble)

library(ggrepel)



is_outlier <- function(x) {
  
  if (is.na(x)==FALSE) {
  return(x < quantile(x, 0.25) - 1.5 * IQR(x) | x > quantile(x, 0.75) + 1.5 * IQR(x)) }
  else{ return(FALSE)}
  
  
}


# mtcars2 <- mtcars %>% tibble::rownames_to_column(var="id") # we put a var "id" 
# # varid -> variable id
# # var1 -> variable to plot
# # varby -> variable to factor boxplot
# # vaird
outlier_idplotter <- function(var1="drat",dat =mtcars2, varby="cyl",varid="id") { ## Had to change the order for the apply

# varid = "id"
# var1 = "mpg"
# varby = "cyl"


dat <- dat %>% group_by(!!sym(varby)) %>% mutate(var = (!!sym(var1)), funs(is_outlier= ifelse(is.na(!!sym(var1)),as.numeric(NA),
                                                                    ifelse( is_outlier(!!sym(var1)),!!sym(var1), as.numeric(NA))) ) )
  
  
 



## id = "something". ¿How do i call this?
dat$id[which(is.na(dat$is_outlier))] <- as.numeric(NA)   # Dont want to do this.
# dat[,"id"][which(is.na(dat[,"is_outlier"]))] <- as.numeric(NA) # Cant get this to work.

# varid = "id"
ggplot(dat, aes(y=!!sym(var1), x=factor(!!sym(varby)))) + geom_boxplot() + geom_text_repel(aes(label=!!sym(varid)),na.rm=TRUE,nudge_y=0.05)


# p+geom_text_repel(data=filter(results, padj<0.05), aes(label=Gene))
}

mtcars2 <- mtcars %>% tibble::rownames_to_column(var="id") # we put a var "id"
(mt_lista = colnames(mtcars2)[c(2,4:6)])
lapply(mt_lista,outlier_idplotter,dat =mtcars2, varby="cyl",varid="id") # Everything good here.

mtcars2_out = mtcars2[15,2]=NA
lapply(mt_lista,outlier_idplotter,dat =mtcars2, varby="cyl",varid="id") ##But now.

1 respuesta 1

1

Entiendo que lo que buscas es que is_outlier() omita los registros NA y regrese el output solo para los datos válidos y NA cuando una fila es NA. En ese caso podrías modificar las llamadas a las funciones que tiene dentro para que se comporten de esa manera. Tanto IQR() como quantile() aceptan el argumento na.rm = , que por defecto es FALSE y regresa un error si se encuentra con un NA.

En ese caso podrías modificar la función:

is_outlier <- function(x) {
    
    x < quantile(x, 0.25, na.rm = TRUE) - 1.5 * IQR(x, na.rm = TRUE) | x > quantile(x, 0.75, na.rm = TRUE) + 1.5 * IQR (x, na.rm = TRUE) }

Me parece que este caso mutate() es solo el mensajero que comunica el error, pero lo hace porque la función que está aplicando (is_outlier()) está pasando un error, que a su lo reporta de la función interna quantile().

¿Resuelve tu problema?

1
  • Sí que lo hace, sí. Lo había "resuelto" filtrando previamente los datos tal que: dat <-dat %>% filter(!is.na(!!sym(var1))) previo a la definición de data. Gracias por la aclaración última porque no entendía por qué mutate no me admitía el argumento, siendo la culpa de la función is_outlier().
    – Galpaccru
    el 4 feb. 2021 a las 11:16

Tu Respuesta

Al pulsar en “Publica tu respuesta”, muestras tu consentimiento a nuestros términos de servicio, política de privacidad y política de cookies

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.