【问题标题】:R- How to reshape Long to Wide with multiple variables/columnsR-如何使用多个变量/列将 Long 重塑为 Wide
【发布时间】:2021-10-06 04:25:50
【问题描述】:

我从以下数据子集开始

UserID labelnospaces             responses
1      Were you given any info?  yes
1      By using this service..?  yes
1      How satisfied are you?    Very satisfied
2      Were you given any info?  no
2      By using this service..?  no
2      How satisfied are you?    unsatisfied

通过使用下面的代码,我能够完美地从长到宽

service_L_to_W<- reshape(data=service, idvar="UserID",
                         timevar = "labelnospaces",  
                         direction = "wide")

使用上面的代码,我得到了(这就是我想要的)

UserID   Were you given any info?   By using this service..?   How satisfied are you?
1        yes                        yes                        very satisfied
2        no                         no                         unsatisfied

我的问题是如何编辑我的代码,以便我可以将我的数据(带有额外的变量/列)从长转换为宽:

UserID Full Name  DOB     EncounterID QuestionID Name  Type  labelnospaces           responses    
1      John Smith 1-1-90  13          505        Intro Check Were you given any info?  yes
1      John Smith 1-1-90  13          506        Care  Check By using this service..   yes
1      John Smith 1-1-90  13          507        Out   Check How satisfied are you?    vsat
2      Jane Doe   2-2-80  14          505        Intro Check Were you given any info?  no
2      Jane Doe   2-2-80  14          506        Care  Check By using this service..   no
2      Jane Doe   2-2-80  14          507        Out   Check How satisfied are you?    unsat

【问题讨论】:

  • 您的预期输出效果如何?你在找tidyr::pivot_wider(df, id_cols = c(UserID, Full.Name, DOB, EncounterID, Type), names_from = labelnospaces, values_from = responses)
  • @RonakShah 谢谢!

标签: r reshape reshape2


【解决方案1】:

一些变量可以更好地结合在一起

df %>%
  pivot_wider(id_cols = c(UserID, Full.Name, DOB, EncounterID), names_from = c(QuestionID, QName, labelnospaces), values_from = responses)

  UserID Full.Name  DOB    EncounterID `505_Intro_Were you given any info?` `506_Care_By using this service..`
   <int> <chr>      <chr>        <int> <chr>                                <chr>                             
1      1 John Smith 1-1-90          13 yes                                  yes                               
2      2 Jane Doe   2-2-80          14 no                                   no                                
  `507_Out_How satisfied are you?`
  <chr>                           
1 vsat                            
2 unsat

【讨论】:

    猜你喜欢
    • 2022-12-13
    • 2021-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多