viernes, 6 de septiembre de 2013

Reformando data usando Reshape2

Reshaping data

Reshaping data

Ejemplo de melting data Dado que la data no siempre se obtiene de la forma en que la necesitamos, debemos poder reformarla de tal manera que podamos operar sobre ella. R cuenta además de funciones propias (tapply, by, aggregate, reshape), con dos paquetes diseñados especialmente para reformatear data: reshape y reshape2. Este último es una nueva versión de reshape. Veamos algunos ejemplos sobre como remodelar data usando las datas que vienen con estos paquetes y siguiendo el manual generado por el Dr. Hadley Wickham, quien ademos creó este paquete y ha creado unos cuántos más. Haremos un ejercicio con la data con la que viene el paquete, y luego haremos dos ejercicios con datos propios.

Cargamos el paquete reshape y reshape2:

require(reshape)
## Loading required package: reshape Loading required package: plyr
## 
## Attaching package: 'reshape'
## 
## The following object is masked from 'package:plyr':
## 
## rename, round_any
require(reshape2)
## Loading required package: reshape2
## 
## Attaching package: 'reshape2'
## 
## The following object is masked from 'package:reshape':
## 
## colsplit, melt, recast
data(smiths)

La data smiths tiene la típica forma de matriz de datos, o lo que en R se conoce como data frame, una hoja de datos:

smiths
##      subject time age weight height
## 1 John Smith    1  33     90   1.87
## 2 Mary Smith    1  NA     NA   1.54

Dependiendo del tipo de análisis, posiblemente necesitemos darle un formato distinto a esta data. Un primer paso para ello es
fusionar la data para luego reorganizarla en la forma que sea más conveniente para nuestros análisis. Eso puede hacerse mediante las funciones melt y cast. Veamos las diferentes posibilidades:

melt(smiths)  # dejamos que la función encuentre los valores y los identificadores. Esto a veces funciona bien, pero no necesariamente todo el tiempo.
## Using subject as id variables
##      subject variable value
## 1 John Smith     time  1.00
## 2 Mary Smith     time  1.00
## 3 John Smith      age 33.00
## 4 Mary Smith      age    NA
## 5 John Smith   weight 90.00
## 6 Mary Smith   weight    NA
## 7 John Smith   height  1.87
## 8 Mary Smith   height  1.54

Normalmente colocamos los casos en filas y las variables en columnas. La función melting nos ayuda a visualizar la data desde otra perspectiva. Como un conjunto de valores y de identificadores de esos valores. De allí que se haya creado una variable identificadora denominada subject se han agrupado las variables y se ha generado la columna de los valores con los que corresponde a cada variable. Se Puede crear una organización más precisa. Para ello es necesario “decirle” a reshape qué variables queremos como qué:

melt(smiths, id = c("subject", "time"), measured = c("age", "weight", "height"))
##      subject time variable value
## 1 John Smith    1      age 33.00
## 2 Mary Smith    1      age    NA
## 3 John Smith    1   weight 90.00
## 4 Mary Smith    1   weight    NA
## 5 John Smith    1   height  1.87
## 6 Mary Smith    1   height  1.54

Nótese que se han seleccionado dos identificadores, subject y time, y las variables restantes se han empleado como valores. Otras posibilidades son:

melt(smiths, id = c("subject", "time"))  #solo se eligen los identificadores
##      subject time variable value
## 1 John Smith    1      age 33.00
## 2 Mary Smith    1      age    NA
## 3 John Smith    1   weight 90.00
## 4 Mary Smith    1   weight    NA
## 5 John Smith    1   height  1.87
## 6 Mary Smith    1   height  1.54
melt(smiths, id = 1:2)
##      subject time variable value
## 1 John Smith    1      age 33.00
## 2 Mary Smith    1      age    NA
## 3 John Smith    1   weight 90.00
## 4 Mary Smith    1   weight    NA
## 5 John Smith    1   height  1.87
## 6 Mary Smith    1   height  1.54
melt(smiths, measured = c("age", "weight", "height"))  #solo se eligen los valores
## Using subject as id variables
##      subject variable value
## 1 John Smith     time  1.00
## 2 Mary Smith     time  1.00
## 3 John Smith      age 33.00
## 4 Mary Smith      age    NA
## 5 John Smith   weight 90.00
## 6 Mary Smith   weight    NA
## 7 John Smith   height  1.87
## 8 Mary Smith   height  1.54

Veamos otros ejemplo:

data(french_fries)
dim(french_fries)
## [1] 696   9

La data tiene 669 casos (observaciones) y 9 variables. Veamos como luce la data, inspeccionando sus primeros registros

head(french_fries)
##    time treatment subject rep potato buttery grassy rancid painty
## 61    1         1       3   1    2.9     0.0    0.0    0.0    5.5
## 25    1         1       3   2   14.0     0.0    0.0    1.1    0.0
## 62    1         1      10   1   11.0     6.4    0.0    0.0    0.0
## 26    1         1      10   2    9.9     5.9    2.9    2.2    0.0
## 63    1         1      15   1    1.2     0.1    0.0    1.1    5.1
## 27    1         1      15   2    8.8     3.0    3.6    1.5    2.3

Reformateemos la data usando las cuatro primeras columnas como idenfiticadores:

ffm <- melt(french_fries, id = 1:4, na.rm = TRUE)
head(ffm)
##   time treatment subject rep variable value
## 1    1         1       3   1   potato   2.9
## 2    1         1       3   2   potato  14.0
## 3    1         1      10   1   potato  11.0
## 4    1         1      10   2   potato   9.9
## 5    1         1      15   1   potato   1.2
## 6    1         1      15   2   potato   8.8

Un uso de la data colocada de esta forma es poder crear visualizaciones múltiples (small-multiples), por ejemplo. Si mantenemos la data en su formato original tendríamos que crear las visualizaciones una a una. Por ejemplo:

require(ggplot2)
## Loading required package: ggplot2
qplot(value, data = ffm, geom = "histogram", facets = . ~ variable, binwidth = 1)

plot of chunk unnamed-chunk-1

Tenemos una data con la tasa de la incidencia del cáncer en el mundo. Una inspección a los primeros seis registros:

head(cancer)
##               pais cervica colon.recto esofago higado leucemia mama oral
## 1      afghanistan     2.6         6.5     9.7    3.8      5.3 14.2  2.0
## 2          albania     1.5         7.1     2.4    6.7      5.7 18.4  4.6
## 3          algeria     3.4         8.5     0.5    1.3      2.9 16.9  3.5
## 4          andorra     0.8        14.3     2.5    4.9      3.8 15.5  2.9
## 5           angola    12.5         3.5     4.0    9.6      1.8 13.0  3.6
## 6 antigua and bar.     5.4        13.6     4.6    5.2      4.0 29.8  2.7
##   ovario pancreas pulmon vejiga gdpcapita    region
## 1    1.0      2.3    7.2    4.3       586    menaga
## 2    1.6      8.9   31.0    3.8     4.042    europe
## 3    1.7      1.3   10.6    5.0     5.523    menaga
## 4    1.9      4.6   21.6    4.2    41.517    europe
## 5    1.8      1.3    2.3    1.5     5.318       ssa
## 6    8.5      3.4    8.3    3.1    12.480 caribbean

Si reformamos la data dejando que las función melt() organice la información tenemos:

cancerMelt <- melt(cancer)
## Using pais, gdpcapita, region as id variables
head(cancerMelt)
##               pais gdpcapita    region variable value
## 1      afghanistan       586    menaga  cervica   2.6
## 2          albania     4.042    europe  cervica   1.5
## 3          algeria     5.523    menaga  cervica   3.4
## 4          andorra    41.517    europe  cervica   0.8
## 5           angola     5.318       ssa  cervica  12.5
## 6 antigua and bar.    12.480 caribbean  cervica   5.4

La funcion ha encontrado exactamente el formato que deseabamos. Sin embargo, podríamos también escoger nosotros mismos tanto las variables que funcionan como idenfiticadores, como los valores que deseamos conservar.

No hay comentarios: