如何重新分组分组行的值成为列的数据? (长到宽?)

时间:2016-11-16 17:33:12

标签: r casting reshape melt

我已经四处搜寻了一个充分的答案,我认为这个问题尚未得到解答。基本上,我有一个长格式的数据框,如下所示:

    ID  event_type event_value
    123    A          1.1      
    123    A          1.2
    123    A          "Hello"
    234    B          "Hello"
    456    A          2.8

哪里有多种具有各种值的事件类型。我想要做的是重塑数据,使其看起来像这样

    ID  event_type_A_1 event_type_A_2 event_type_A_3 event_type_B_1
    123    1.1         1.2              "Hello"         NA
    234    NA          NA                NA            "Hello"
    456    2.8         NA                NA             NA

使得新柱延伸到任何给定患者的最长事件类型,其余的用NA填充。我已经使用spread()cast()进行了调整,但由于某种原因它只是没有点击。谢谢!

1 个答案:

答案 0 :(得分:3)

您可以使用dplyrtidyr执行此操作。诀窍是使用group_by并使用mutaterow_number添加组内索引。

library(dplyr)
library(tidyr)

df <- data_frame(ID = c(123,123,123,234,456),
                 event_type = c("A","A","A","B","A"),
                 event_value = c(1.1, 1.2, "Hello", "Hello", 2.8))

df %>%
  group_by(ID) %>% 
  mutate(sub_ID = row_number()) %>% 
  unite("ID_type", event_type, sub_ID,remove = TRUE) %>% 
  spread(ID_type, event_value)

分解dplyr链:

  1. 按ID
  2. 制作小组
  3. 使用row_number()
  4. 创建sub_ID
  5. event_typesub_IDunite合并,删除原始列
  6. spread()将ID_type分配到具有event_value
  7. 值的列中