如何最好地使用R来重塑数据帧从长到宽和组合值



我有一个大约2000行和3列的数据框架。本质上,我想重塑这个数据框,使其更宽而不是更长。这是我当前数据的一个例子:

01/01/2001 01/01/200101/01/200102/02/200102/02/200103/03/200103/03/200104/04/200104/04/200105/05/200105/05/200106/06/200106/06/200107/07/200107/07/2001
library(tidyverse)
df %>%
group_by(ID, Date) %>%
summarize(Procedure = paste0(Procedure, collapse = ", ")) %>%
mutate(col = row_number()) %>%
ungroup() %>%
pivot_wider(names_from = col, values_from = c(Date, Procedure))

这目前需要一些重新排序之后,可以这样做:https://stackoverflow.com/a/60400134/6851825

# A tibble: 4 x 7
ID    Date_1 Date_2 Date_3 Procedure_1                Procedure_2        Procedure_3          
<chr> <chr>  <chr>  <chr>  <chr>                      <chr>              <chr>                
1 A66   2/2/01 NA     NA     Sedation, Excision         NA                 NA                   
2 D55   1/1/01 NA     NA     Sedation, Excision, Biopsy NA                 NA                   
3 G88   5/5/01 6/6/01 7/7/01 Sedation, Biopsy           Sedation, Excision Sedation, Re-excision
4 T44   3/3/01 4/4/01 NA     Sedation, Biopsy           Sedation, Excision NA                   

相关内容

  • 没有找到相关文章

最新更新