簡體   English   中英

R-如何使用多個變量/列將長形重塑為寬形

[英]R- How to reshape Long to Wide with multiple variables/columns

我從以下數據子集開始

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

有些變量放在一起會更好

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM