Filtrar datos.enmarcar filas por una condición lógica


Quiero filtrar filas de un data.frame basado en una condición lógica. Supongamos que tengo un marco de datos como

   expr_value     cell_type
1    5.345618 bj fibroblast
2    5.195871 bj fibroblast
3    5.247274 bj fibroblast
4    5.929771          hesc
5    5.873096          hesc
6    5.665857          hesc
7    6.791656          hips
8    7.133673          hips
9    7.574058          hips
10   7.208041          hips
11   7.402100          hips
12   7.167792          hips
13   7.156971          hips
14   7.197543          hips
15   7.035404          hips
16   7.269474          hips
17   6.715059          hips
18   7.434339          hips
19   6.997586          hips
20   7.619770          hips
21   7.490749          hips

Lo que quiero es obtener un nuevo marco de datos que se vea igual pero solo tenga los datos para un cell_type. Por ejemplo, subconjunto / seleccionar filas que contiene el tipo de celda "hesc":

   expr_value     cell_type
1    5.929771          hesc
2    5.873096          hesc
3    5.665857          hesc

O bien tipo de célula" fibroblasto bj "o"hesc":

   expr_value     cell_type
1    5.345618 bj fibroblast
2    5.195871 bj fibroblast
3    5.247274 bj fibroblast
4    5.929771          hesc
5    5.873096          hesc
6    5.665857          hesc

¿Hay alguna manera fácil de hacer esto?

He intentado:

expr[expr[2] == 'hesc']
# [1] "5.929771" "5.873096" "5.665857" "hesc"     "hesc"     "hesc"    

Si se llama al marco de datos original "expr", pero da los resultados en un formato incorrecto como se puede ver.

Author: Henrik, 2009-11-06

7 answers

expr[expr$cell_type == "hesc", ]

expr[expr$cell_type %in% c("hesc", "bj fibroblast"), ]
 163
Author: learnr,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-11-06 10:08:47

Use subset (para uso interactivo)

subset(expr, cell_type == "hesc")
subset(expr, cell_type %in% c("bj fibroblast", "hesc"))

O mejor dplyr::filter()

filter(expr, cell_type %in% c("bj fibroblast", "hesc"))
 73
Author: rcs,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-25 06:33:21

La razón por la que expr[expr[2] == 'hesc'] no funciona es que para un marco de datos, x[y] selecciona columnas, no filas. Si desea seleccionar filas, cambie a la sintaxis x[y,] en su lugar:

> expr[expr[2] == 'hesc',]
  expr_value cell_type
4   5.929771      hesc
5   5.873096      hesc
6   5.665857      hesc
 27
Author: Ken Williams,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-11-09 17:35:10

Puedes usar el paquete dplyr:

library(dplyr)
filter(expr, cell_type == "hesc")
filter(expr, cell_type == "hesc" | cell_type == "bj fibroblast")
 18
Author: nathaneastwood,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-09-04 13:12:25

A veces la columna que desea filtrar puede aparecer en una posición diferente a la columna índice 2 o tener un nombre de variable.

En este caso, simplemente puede referirse al nombre de la columna que desea filtrar como:

columnNameToFilter = "cell_type"
expr[expr[[columnNameToFilter]] == "hesc", ]
 2
Author: Daniel Bonetti,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-10 14:16:52

Nadie parece haber incluido la función which. También puede resultar útil para filtrar.

expr[which(expr$cell == 'hesc'),]

Esto también manejará el NAS y los soltará del dataframe resultante.

Ejecutando esto en un 9840 por 24 dataframe 50000 veces, parece que el método which tiene un tiempo de ejecución 60% más rápido que el método %in%.

 1
Author: christopher van hoecke,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-18 15:14:13

Estaba trabajando en un dataframe y no tenía suerte con las respuestas proporcionadas, siempre devolvía 0 filas, así que encontré y usé grepl:

df = df[grepl("downlink",df$Transmit.direction),]

Que básicamente recortó mi dataframe a solo las filas que contenían "enlace descendente" en la columna de dirección de transmisión. PD Si alguien puede adivinar por qué no veo el comportamiento esperado, por favor deje un comentario.

Específicamente a la pregunta original:

expr[grepl("hesc",expr$cell_type),]

expr[grepl("bj fibroblast|hesc",expr$cell_type),]
 0
Author: Justin Harbour,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-06 21:46:29