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

后端 未结 4 678
旧巷少年郎
旧巷少年郎 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:02

    If your data is in a data.table it's a one-liner can be done as follows:

    library(data.table)    
    mturk.dt <- as.data.table(mturk)
    
    mturk.dt[, as.list(
             rbind(c(Answer.Q1thing, AssignmentStatus))
             )
            , by=list(Id=Input.id, State=Input.State)]
    

    Note that the by argument handles the name-changing too!


    If you want to properly name the other columns, use setnames after the fact or, more dynamically, using setattr within the j=.. argument as follows:

    After the Fact:

    ## Assuming 'res' is the reshaped data.table form above:
    ## Change the names of the six V1, V2.. columns 
    setnames(res, paste0("V", 1:6), c(paste0("Answer", 1:3), paste0("Status", 1:3)))
    

    Dynamically, in j=..

    ## Use `as.data.table` instead of `as.list`, to preserve new names
    mturk.dt[, as.data.table(
             rbind(c(
                  setattr(Answer.Q1thing,   "names", paste0("Answer", seq(Answer.Q1thing  )))
                , setattr(AssignmentStatus, "names", paste0("Status", seq(AssignmentStatus)))
                ))
             )
            , by=list(Id=Input.id, State=Input.State)]
    
           Id State Answer1 Answer2  Answer3  Status1  Status2  Status3
    1: 134231    NY Myguess Myguess BadGuess Approved Approved Approved
    2: 134812    CA Myguess Myguess BadGuess Approved Approved Approved
    

提交回复
热议问题