1

Tengo un dataframe como este:

 min   max   lib       ncbi   
 241   491   PV514   NC_003651
 241   594   PV514   NC_003651
 696   787   PV514   NC_003651
 241   491   PV091   NC_003651
 241   506   PV015   NC_006421
 504   704   PV015   NC_006421
 940   1080  PV514   NC_006421

Y me gustaría agrupar los valores de las columnas de min y max cuando solapen y sean del mismo valor de la lib y del mismo ncbi

 min   max   lib       ncbi         ssdif
 241   594   PV514   NC_003651       353
 696   787   PV514   NC_003651       91
 241   491   PV091   NC_003651       250
 241   704   PV015   NC_006421       463
 940   1080  PV514   NC_006421       140

Para que posteriormente se sumen los valores de ssdif de las filas que tienen el mismo valor de lib y ncbi

    lib       ncbi         ssdif
    PV514   NC_003651       444
    PV091   NC_003651       250
    PV015   NC_006421       463
    PV514   NC_006421       140

He intentando agruparlo con la función group_by pero no se que función añadir para que distinga entre rangos que solapen.

2 respuestas 2

1

El principal problema es como definir cada grupo. La forma más sencilla es, en primer lugar asegurarse de tener los datos ordenados secuencialmente por lib, ncbi, min y max, luego hay que "visitar" cada fila y compararla con la anterior, sí lib, ncbi cambian o el min actual es mayor al max anterior, estamos frente a un nuevo grupo.

Cargamos el ejemplo:

library("tidyverse")

df <- read.table(text="min   max   lib       ncbi   
 241   491   PV514   NC_003651
 241   594   PV514   NC_003651
 696   787   PV514   NC_003651
 241   491   PV091   NC_003651
 241   506   PV015   NC_006421
 504   704   PV015   NC_006421
 940   1080  PV514   NC_006421", header=TRUE, stringsAsFactors=FALSE)

Procesamos:

df %>%
  arrange(lib, ncbi, min, max) %>% 
  mutate(grupo = cumsum(case_when(
    is.na(lag(lib)) ~ 1,    # el primer caso es nuevo grupo
    lib != lag(lib) ~ 1,    # cambió lib, nuevo grupo
    ncbi != lag(ncbi) ~ 1,  # cambió ncbi nuevo grupo
    min > lag(max) ~ 1,     # si el mínimo es mayor al máximo anterior, nuevo grupo
    TRUE ~ 0                # Sino esta fila no cambia de grupo
  ))) %>% 
  group_by(lib, ncbi, grupo) %>% 
  summarise(ssdif = max(max) - min(min))

Resultado:

# A tibble: 5 x 4
# Groups:   lib, ncbi [4]
  lib   ncbi      grupo ssdif
  <chr> <chr>     <dbl> <int>
1 PV015 NC_006421     1   463
2 PV091 NC_003651     2   250
3 PV514 NC_003651     3   353
4 PV514 NC_003651     4    91
5 PV514 NC_006421     5   140
1
  • Funciona! El único problema es que mi tabla es de alrededor de 13000000 de filas y necesita mucho tiempo de procesamiento con esas funciones, pero lo ejecuto y no me da ningún fallo, aunque sigo esperando aún el output.Gracias de antemano el 5 may. 2020 a las 14:24
1

Eventualmente, si tienes problemas de performance, podrías probar usando R base:

# Ordenamos
df <- df[order(df$lib, df$ncbi, df$min, df$max), ]

# Generamos para cada fila el valor de la fila anterior
df$lib_ant <- c(NA,head(df$lib,-1))
df$ncbi_ant <- c(NA,head(df$ncbi,-1))
df$max_ant <- c(NA,head(df$max,-1))
# Armamos los grupos
df$grupo <- cumsum(
              ifelse(is.na(df$lib_ant), 1, 
                     ifelse(df$lib != df$lib_ant, 1,
                            ifelse(df$ncbi != df$ncbi_ant, 1,
                                   ifelse(df$min > df$max_ant, 1, 0)
                                   )
                            )
                     )
              )
# Finalmente agrupamos
df.agrupado <- aggregate(max ~ lib + ncbi + grupo, df, max)
df.agrupado$min <- aggregate(min ~ lib + ncbi + grupo, df, min)$min
df.agrupado$ssdif <- df.agrupado$max - df.agrupado$min

df.agrupado

    lib      ncbi grupo  max min ssdif
1 PV015 NC_006421     1  704 241   463
2 PV091 NC_003651     2  491 241   250
3 PV514 NC_003651     3  594 241   353
4 PV514 NC_003651     4  787 696    91
5 PV514 NC_006421     5 1080 940   140
0

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.