Reshaping several variables wide with cast

后端 未结 3 645
自闭症患者
自闭症患者 2020-12-16 03:56

I have a data.frame that looks like this:

> head(ff.df)
  .id pio caremgmt prev price surveyNum
1   1   2        2    1     2         1
2   1   2        1         


        
3条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-16 04:22

    I think the problem is that ff.df is not yet sufficiently molten. Try this:

    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
    

    Does that do the trick for you?

    Essentially, when casting, the variables indicated on the right-hand side of the casting formula dictate the columns that will appear in the cast result. By indicating only .id, I believe that you were asking cast to somehow cram all of those vectors of values into just three columns - 1, 2, and 3. Melting the data all the way down creates the variable column, which lets you specify that the combination of the .id and variable vectors should define the columns of the cast data frame.

    (Sorry if I'm being repetitious/pedantic! I'm trying to work it out for myself, too)

提交回复
热议问题