R长到宽格式的类别变量和日期

时间:2019-05-20 13:53:27

标签: r tidyverse reshape2 dcast

我想制作一个长格式的数据集,并使用分类变量(药物)将开始和结束日期设置为宽格式。结果,每个ID应该有一行,并且对于每种药物,每列有条目1/0的列表示患者是否接受了药物。并且药物列应具有相应的开始日期和结束日期作为额外列。

我想

test <- data.frame(
  PatID  = c(1L, 1L, 2L, 2L, 3L, 4L,4L),
  medication = c("Jak","Others", "HU", "Inf","Others", "HU","Others"),  startDate   = c("2016-12-14", "2017-02-04", "2016-03-26", "2016-06-13", "2012-27-03", "2012-04-21", "2010-02-03"),
  endDate   = c("2018-11-14", "2018-02-25", "2017-06-13", "2017-11-12", "2018-27-03", "2016-04-30", "2016-08-16")
)

输出应为以下

ID   Jak   Jak_startDate   Jak_endDate   HU   HU_startDate   HU_endDate   Inf   Inf_startDate   Inf_endDate   Others   Others_startDate   Others_endDate <br/>
1    1      2016-12-14    2018-11-14     0     NA                NA        0        NA             NA            1      2017-02-04        2018-02-25
2    0         NA               NA       1   2017-06-13   2017-11-12       1   2018-03-27   2016-04-30           0         NA               NA
3    0         NA               NA       0     NA                NA        0        NA             NA            1      2012-27-03        2018-27-03
4    0         NA               NA       1   2012-04-21   2016-04-30       0        NA             NA            1      2010-02-03        2016-08-16

1 个答案:

答案 0 :(得分:0)

使用os.remove()是我所做的:

tidyverse

在这里,我将数据加长,然后根据test %>% gather(key, value, - PatID, -medication) %>% arrange(PatID, value) %>% mutate(new_key = paste(medication, key, sep = "_")) %>% select(PatID, new_key, value) %>% spread(new_key, value) %>% left_join(test %>% select(PatID, medication) %>% mutate(ind = 1) %>% spread(medication, ind)) arrange PatID。然后,我仅使用三个变量创建一个新的键列valuenew_keyselectPatIDnew_key。然后,我将所有这些都转换为广泛的数据,但是我们仍然需要列valueJak等,它们似乎是指标变量。为此,我在HU中获取了测试数据,并left_join来获取您所请求的列。