Extracción de columnas específicas de un marco de datos


Tengo un marco de datos R con 6 columnas, y quiero crear un nuevo marco de datos que solo tenga tres de las columnas.

Suponiendo que mi marco de datos es df, y quiero extraer columnas A, B, y E, este es el único comando que puedo averiguar:

 data.frame(df$A,df$B,df$E)

Hay una forma más compacta de hacer esto?

 287
Author: Aren Cambre, 2012-04-10

8 answers

Usando el paquete dplyr, si sus datos.el marco se llama df1:

library(dplyr)

df1 %>%
  select(A, B, E)

Esto también se puede escribir sin la tubería %>% como:

select(df1, A, B, E)
 45
Author: Sam Firke,
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
2015-04-19 21:19:17

Puede realizar subconjuntos utilizando un vector de nombres de columna. Prefiero fuertemente este enfoque sobre aquellos que tratan los nombres de columna como si fueran nombres de objetos (por ejemplo, subset()), especialmente cuando se programa en funciones, paquetes o aplicaciones.

# data for reproducible example
# (and to avoid confusion from trying to subset `stats::df`)
df <- setNames(data.frame(as.list(1:5)), LETTERS[1:5])
# subset
df[,c("A","B","E")]
 376
Author: Joshua Ulrich,
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-09-07 22:18:16

Este es el papel de la subset() función:

> dat <- data.frame(A=c(1,2),B=c(3,4),C=c(5,6),D=c(7,7),E=c(8,8),F=c(9,9)) 
> subset(dat, select=c("A", "B"))
  A B
1 1 3
2 2 4
 83
Author: Stéphane Laurent,
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-01-15 00:24:29

Hay dos opciones obvias: la de Joshua Ulrich df[,c("A","B","E")] o

df[,c(1,2,5)]

Como en

> df <- data.frame(A=c(1,2),B=c(3,4),C=c(5,6),D=c(7,7),E=c(8,8),F=c(9,9)) 
> df
  A B C D E F
1 1 3 5 7 8 9
2 2 4 6 7 8 9
> df[,c(1,2,5)]
  A B E
1 1 3 8
2 2 4 8
> df[,c("A","B","E")]
  A B E
1 1 3 8
2 2 4 8
 55
Author: Henry,
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
2012-04-10 06:49:54

También puede usar el paquete sqldf que realiza selects en R data frames como:

df1 <- sqldf("select A, B, E from df")

Esto da como resultado un marco de datos df1 con columnas: A ,B, E.

 10
Author: Aman Burman,
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-04-20 16:57:16

De nuevo usando dplyr, donde df1 es su marco de datos original:

df2 <- subset(df1, select = c(1, 2, 5))
 8
Author: Richard Ball,
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-10 11:34:19

Por alguna razón solamente

df[, (names(df) %in% c("A","B","E"))]

Funcionó para mí. Todas las sintaxis anteriores produjeron "columnas indefinidas seleccionadas".

 5
Author: so860,
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-10-12 18:12:23

[ y subconjunto no son sustituibles:

[ devuelve un vector si solo se selecciona una columna.

df = data.frame(a="a",b="b")    

identical(
  df[,c("a")], 
  subset(df,select="a")
) 

identical(
  df[,c("a","b")],  
  subset(df,select=c("a","b"))
)
 0
Author: fxi,
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-11-09 15:32:24