【问题标题】:Reshape a dataframe continaing nominal data where value becomes column prefix重塑包含标称数据的数据框,其中值成为列前缀
【发布时间】:2020-01-10 13:24:38
【问题描述】:

问候同事,我正在努力解决一个基本问题,但似乎无法解决我的问题。我有一个结构如下的数据集:

Reference | Person | DOB       |Status      | Address
------------------------------------------------------
0001/xy   | 001    |19/01/1960 | Respondent |123 Fake Street
0001/xy   | 002    |01/06/1978 | Defendant  |555 High Ave.
0002/xy   | 001    |31/04/1988 | Respondent |432 Random Dr.
0002/xy   | 002    |14/07/1991 | Defendant  |666 Missing Close
0002/xy   | 003    |10/10/2010 | Defendant  |987 McFakerton Blvd.
0003/xy   | 001    |08/02/1995 | Respondent |911 Crime Street

Reference 是“事件”的唯一键 我需要的是单行宽数据集,其中要旋转的列是 Status 并且新列包含来自值的前缀柱子。所以它应该看起来像;

Reference | Person | Respondent1_DOB | Respondent1_Address |Defendent1_DOB | Defendent1_Address |Defendent2_DOB | Defendent2_Address 
-------------------------------------------------------------------------------------------------------------------------------------
0001/xy   | 001    |19/01/1960       |123 Fake Street      |01/06/1978     |555 High Ave        |               |
0002/xy   | 001    |31/04/1988       |432 Random Dr.       |14/07/1991     |666 Missing Close   |10/10/2010     |987 McFakerton Blvd 
0003/xy   | 001    |08/02/1995       |911 Crime Street     |               |                    |               |

正如您所看到的,这是一项简单的任务,但我尝试过的所有重塑功能,包括tidyrReshape2continue 尝试总结去除名义特征的数据,除了不重复列标题对于提供的值,或者完全失败。

我目前尝试过的失败代码包括:

Trans<-transform(reshape(Original, direction='wide', 
                                varying=list(3,5))[-1], id=Status)

Trans<- dcast(Original, Reference ~ Status, 
               value.var = c("DOB","Address"))

Trans<- Original %>% pivot_wide(Reference ~ Status,names_preifx=Status )

在 R 中有一种简单的方法可以做到这一点吗?我可以用 Python 来做,但我试图坚持使用一种语言和 IDE,因为这是该组织目前所拥有的。

【问题讨论】:

    标签: r transform tidyr reshape2


    【解决方案1】:

    你可以使用 base r reshape 函数:

    reshape(df[-4],timevar = "Person",idvar = "Reference",direction = "wide")
    
      Reference    DOB.001      Address.001    DOB.002       Address.002    DOB.003          Address.003
    1   0001/xy 19/01/1960  123 Fake Street 01/06/1978     555 High Ave.       <NA>                 <NA>
    3   0002/xy 31/04/1988   432 Random Dr. 14/07/1991 666 Missing Close 10/10/2010 987 McFakerton Blvd.
    6   0003/xy 08/02/1995 911 Crime Street       <NA>              <NA>       <NA>                 <NA>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-29
      • 2020-12-27
      相关资源
      最近更新 更多