Esistono diverse risorse sul sito Web di Hadley Wickham per il pacchetto (ora chiamato reshape2
), incluso un collegamento a un documento sul pacchetto nel Journal of Statistical Software.
Ecco un breve esempio dall'articolo:
> require(reshape2)
Loading required package: reshape2
> data(smiths)
> smiths
subject time age weight height
1 John Smith 1 33 90 1.87
2 Mary Smith 1 NA NA 1.54
Notiamo che i dati sono in formato ampio. Per passare alla forma lunga, facciamo il smiths
frame di dati fuso :
> melt(smiths)
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
Nota come ho melt()
scelto una delle variabili come id, ma possiamo indicare esplicitamente quale utilizzare tramite argomento 'id'
:
> melt(smiths, id = "subject")
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
Ecco un altro esempio da ?cast
:
#Air quality example
names(airquality) <- tolower(names(airquality))
aqm <- melt(airquality, id=c("month", "day"), na.rm=TRUE)
Se memorizziamo il frame di dati fuso, possiamo eseguire il cast in altre forme. Nella nuova versione di reshape
(chiamato reshape2
) ci sono funzioni acast()
che dcast()
restituiscono rispettivamente un risultato simile a un array (array, matrice, vettore) o un frame di dati. Queste funzioni assumono anche una funzione di aggregazione (ad esempio mean()
) per fornire riepiloghi di dati in forma fusa. Ad esempio, seguendo l'esempio di qualità dell'aria sopra riportato, possiamo generare, in forma ampia, valori medi mensili per le variabili nel set di dati:
> dcast(aqm, month ~ variable, mean)
month ozone solar.r wind temp
1 5 23.61538 181.2963 11.622581 65.54839
2 6 29.44444 190.1667 10.266667 79.10000
3 7 59.11538 216.4839 8.941935 83.90323
4 8 59.96154 171.8571 8.793548 83.96774
5 9 31.44828 167.4333 10.180000 76.90000
In realtà ci sono solo due funzioni principali in reshape2
: melt()
e the acast()
e dcast()
pairing. Guarda gli esempi nelle pagine di aiuto per queste due funzioni, vedi il sito Web di Hadley (link sopra) e guarda il documento che ho citato. Questo dovrebbe iniziare.
Potresti anche esaminare il plyr
pacchetto di Hadley che fa cose simili reshape2
ma è progettato per fare molto di più.