Reshape in R without aggregation (for example MTurk response strings)

后端 未结 4 687
旧巷少年郎
旧巷少年郎 2021-01-21 09:16

Ordinarily, I\'d use a pretty basic long-to-wide reshape for this, but it seems to be dropping my aggregation variables. The setup is I had a job on mechanical Turk that I perfo

4条回答
  •  执念已碎
    2021-01-21 10:15

    From data.table v1.9.5+, dcast can handle multiple value.var columns, i.e., we can cast multiple columns simultaneously. We can simply do:

    dt[, id := seq_len(.N), by=Input.id]
    dcast(dt, Input.id + Input.State ~ id, 
            value.var=c("AssignmentStatus", "Answer.Q1thing"))
    #    Input.id Input.State 1_AssignmentStatus 2_AssignmentStatus 3_AssignmentStatus
    # 1:   134231          NY           Approved           Approved           Approved
    # 2:   134812          CA          Submitted           Approved           Approved
    #    1_Answer.Q1thing 2_Answer.Q1thing 3_Answer.Q1thing
    # 1:          Myguess          Myguess         BadGuess
    # 2:          Another          Another          Another
    

    Or everything together in one line:

    dcast(dt, Input.id + Input.State ~ dt[, seq_len(.N), by=Input.id]$V1, 
                     value.var=c("AssignmentStatus", "Answer.Q1thing"))
    

提交回复
热议问题