Reshaping data frame with duplicates

后端 未结 4 2139
庸人自扰
庸人自扰 2020-12-01 15:19

I have what should be a simple reshaping problem, but I can\'t figure it out. Part of my data looks like this:

foo <- structure(list(grade = c(3, 3, 4, 4,         


        
4条回答
  •  庸人自扰
    2020-12-01 15:58

    If you want to reshape and you have duplicates, you're going to need to give each pair a unique id:

    foorle <- rle(foo$grade)
    fooids <- rep(seq_len(length(foorle$values)), times=foorle$lengths)
    
    fooids
     [1]  1  1  2  2  3  3  4  4  5  5  6  6  7  7  8  8  9  9 10 10
    

    Now you'll be able to use reshape properly:

    idfoo <- cbind(id=fooids, foo)
    
    library(reshape)
    dcast(idfoo, id+grade~var.type, value.var="var.val")
    
       id grade SE  SS
    1   1     3 47 120
    2   2     4 46 120
    3   3     5 46 120
    4   4     6 47 120
    5   5     7 46 120
    6   6     8 46 120
    7   7     3 12 120
    8   8     4 14 120
    9   9     5 16 120
    10 10     6 20 120
    

    EDIT: Please note I'm assuming your data is in order, else you'll have problems distinguishing between duplicates. If it isn't, you can always use order so that it is.

提交回复
热议问题