2012-04-06 17 views
8

que tienen un hoja.de.datos que tiene este aspecto:Remodelación de varias variables de ancho con el elenco

> head(ff.df) 
    .id pio caremgmt prev price surveyNum 
1 1 2  2 1  2   1 
2 1 2  1 2  1   2 
3 1 1  1 2  2   3 
4 1 2  2 1  5   4 
5 1 1  1 1  3   5 
6 1 1  2 2  4   6 

me gustaría remodelar las cuatro variables no-id de ancho por ID. En otras palabras, quiero COLNAMES:

surveyNum pio1 pio2 pio3 caremgmt1 caremgmt2 caremgmt3 prev1 prev2 prev3 price1 price2 price3 

puedo hacer que para una sola variable:

> cast(ff.df, surveyNum~.id, value=c("pio")) 
    surveyNum 1 2 3 
1   1 2 2 2 
2   2 2 1 2 
3   3 1 2 1 
4   4 2 1 1 
5   5 1 2 2 
6   6 1 2 1 
7   7 1 1 2 
8   8 2 2 1 
9   9 1 1 2 
10  10 1 1 1 
11  11 2 2 1 
12  12 1 2 2 
13  13 1 1 1 
14  14 2 1 1 
15  15 1 2 1 
16  16 2 1 2 
17  17 1 2 2 
18  18 2 1 2 
19  19 1 2 2 
20  20 2 2 2 
21  21 2 1 1 
22  22 1 2 1 
23  23 2 1 1 
24  24 2 1 2 

Pero cuando lo intento para unos pocos que sólo falla completamente:

> cast(ff.df, surveyNum~.id, value=c("pio","caremgmt","prev","price")) 
Error in data.frame(data[, c(variables), drop = FALSE], result = data$value) : 
    arguments imply differing number of rows: 72, 0 
In addition: Warning message: 
In names(data) == value : 
    longer object length is not a multiple of shorter object length 

¿Algún consejo? Puedo utilizar la base (Estadísticas) reshape de comandos, pero realmente estoy tratando de alejarse de él, ya que provoca demasiados traumas cuero cabelludo manual desde tirones de pelo ....

ff.df <- structure(list(.id = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 3L, 3L, 
3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 
3L, 3L, 3L, 3L, 3L, 3L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 
    2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), pio = structure(c(2L, 
2L, 1L, 2L, 1L, 1L, 1L, 2L, 1L, 1L, 2L, 1L, 1L, 2L, 1L, 2L, 1L, 
2L, 1L, 2L, 2L, 1L, 2L, 2L, 2L, 2L, 1L, 1L, 2L, 1L, 2L, 1L, 2L, 
1L, 1L, 2L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 2L, 2L, 
1L, 2L, 1L, 2L, 2L, 1L, 2L, 1L, 1L, 2L, 2L, 1L, 1L, 2L, 1L, 2L, 
1L, 2L, 2L, 1L, 2L, 1L, 1L), .Label = c("1", "2"), class = "factor"), 
    caremgmt = structure(c(2L, 1L, 1L, 2L, 1L, 2L, 2L, 1L, 1L, 
    2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 1L, 1L, 2L, 
    1L, 2L, 1L, 2L, 1L, 1L, 2L, 2L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 
    1L, 2L, 1L, 2L, 1L, 1L, 2L, 1L, 2L, 1L, 2L, 2L, 2L, 2L, 1L, 
    1L, 2L, 1L, 2L, 1L, 1L, 1L, 1L, 2L, 1L, 2L, 2L, 2L, 1L, 1L, 
    1L, 2L, 2L), .Label = c("1", "2"), class = "factor"), prev = structure(c(1L, 
    2L, 2L, 1L, 1L, 2L, 1L, 2L, 2L, 1L, 2L, 2L, 2L, 2L, 1L, 1L, 
    1L, 2L, 2L, 1L, 2L, 1L, 1L, 1L, 2L, 1L, 2L, 2L, 1L, 1L, 1L, 
    2L, 1L, 1L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 1L, 1L, 
    2L, 2L, 2L, 2L, 1L, 2L, 1L, 1L, 2L, 1L, 1L, 1L, 2L, 1L, 2L, 
    1L, 2L, 1L, 1L, 1L, 2L, 2L, 1L, 2L, 2L, 2L), .Label = c("1", 
    "2"), class = "factor"), price = structure(c(2L, 1L, 2L, 
    5L, 3L, 4L, 1L, 5L, 4L, 3L, 1L, 2L, 6L, 6L, 5L, 4L, 6L, 3L, 
    5L, 6L, 3L, 1L, 2L, 4L, 3L, 5L, 2L, 5L, 4L, 5L, 6L, 6L, 4L, 
    6L, 4L, 1L, 2L, 3L, 1L, 2L, 2L, 5L, 1L, 6L, 1L, 3L, 4L, 3L, 
    6L, 5L, 5L, 4L, 4L, 2L, 2L, 2L, 6L, 3L, 1L, 4L, 4L, 5L, 1L, 
    3L, 6L, 1L, 3L, 5L, 1L, 3L, 6L, 2L), .Label = c("1", "2", 
    "3", "4", "5", "6"), class = "factor"), surveyNum = c(1L, 
    2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L, 14L, 
    15L, 16L, 17L, 18L, 19L, 20L, 21L, 22L, 23L, 24L, 1L, 2L, 
    3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L, 14L, 15L, 
    16L, 17L, 18L, 19L, 20L, 21L, 22L, 23L, 24L, 1L, 2L, 3L, 
    4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L, 14L, 15L, 16L, 
    17L, 18L, 19L, 20L, 21L, 22L, 23L, 24L)), .Names = c(".id", 
"pio", "caremgmt", "prev", "price", "surveyNum"), row.names = c(NA, 
-72L), class = "data.frame") 
+0

pregunta relacionada: http://stackoverflow.com/questions/27247078/reshape-multiple-values-at- una vez en r – landroni

Respuesta

13

Creo que el problema es que ff.df aún no está lo suficientemente fundido. Pruebe esto:

library(reshape) 

# Melt it down 
ff.melt <- melt(ff.df, id.var = c("surveyNum", ".id")) 

# Note the new "variable" column, which will be combined 
# with .id to make each column header 
head(ff.melt) 

    surveyNum .id variable value 
1   1 1  pio  2 
2   2 1  pio  2 
3   3 1  pio  1 
4   4 1  pio  2 
5   5 1  pio  1 
6   6 1  pio  1 

# Cast it out - note that .id comes after variable in the formula; 
# I think the only effect of that is that you get "pio_1" instead of "1_pio" 
ff.cast <- cast(ff.melt, surveyNum ~ variable + .id) 

head(ff.cast) 

    surveyNum pio_1 pio_2 pio_3 caremgmt_1 caremgmt_2 caremgmt_3 prev_1 prev_2 prev_3 price_1 price_2 price_3 
1   1  2  2  2   2   1   1  1  2  2  2  6  3 
2   2  2  1  2   1   2   2  2  2  1  1  5  5 
3   3  1  2  1   1   2   1  2  1  2  2  5  2 
4   4  2  1  1   2   2   2  1  2  2  5  4  5 
5   5  1  2  2   1   2   1  1  1  1  3  4  4 
6   6  1  2  1   2   1   1  2  1  1  4  2  5 

¿Eso le parece el truco para usted?

Esencialmente, cuando se lanza, las variables indicadas en el lado derecho de la fórmula de lanzamiento dictan las columnas que aparecerán en el resultado del lanzamiento. Al indicar solo .id, creo que estaba pidiendo cast de alguna manera meter todos esos vectores de valores en solo tres columnas - 1, 2 y 3. La fusión de los datos hasta el fondo crea la columna variable, que le permite especificar que la combinación de los vectores .id y variable debe definir las columnas del marco de datos de imágenes moldeadas.

(Lo siento si estoy siendo repetitivo/pedante! Estoy tratando de trabajar por mí mismo, también)

+2

PD: 'reshape2' ha existido desde hace un tiempo, y realmente es mucho más rápido que el original. Vea [el anuncio de Hadley] (https://stat.ethz.ch/pipermail/r-packages/2011/001204.html). El único cambio que necesitaría hacer en el código anterior es cambiar 'cast()' a 'dcast()'. –

+0

Eso hace el truco. ¡Gracias! Un paso más en mi camino para "arrojar" la iluminación. –

+0

Re: tu comentario. Creo que lo quiero como '.id ~ variable' ya que afecta el orden del data.frame final. –

7

Usted puede hacer esto con la función reshape en base R. El ordenamiento columna es un poco extraño, pero se puede arreglar fácilmente.

reshape(ff.df, direction = 'wide', idvar = "surveyNum", timevar = '.id') 
+0

Estoy de acuerdo, y estoy definitivamente más familiarizado con 'reshape' que con' cast' (aunque yo uso 'melt' todo el tiempo), pero realmente desprecio la sintaxis' remhape' así que evito usarlo. –

+0

Sí. 'reshape' es brillante pero con una sintaxis innecesariamente compleja. Podría escribir un envoltorio alrededor de eso algún día. – Ramnath

+0

Empecé a usar una remodelación básica hace aproximadamente un mes. La sintaxis es terrible pero es extremadamente poderosa. +1 –

4

Usted puede hacer esto utilizando dcast de la versión rrollo de data.table es decir v1.9.5

library(data.table) 
    ff.cast <- dcast(setDT(ff.df), surveyNum~.id, 
     value.var=c('pio', 'caremgmt', 'prev', 'price')) 
    head(ff.cast,3) 
    # surveyNum 1_pio 2_pio 3_pio 1_caremgmt 2_caremgmt 3_caremgmt 1_prev 2_prev 
    #1:   1  2  2  2   2   1   1  1  2 
    #2:   2  2  1  2   1   2   2  2  2 
    #3:   3  1  2  1   1   2   1  2  1 
    # 3_prev 1_price 2_price 3_price 
    #1:  2  2  6  3 
    #2:  1  1  5  5 
    #3:  2  2  5  2 
Cuestiones relacionadas