r - Grouping key/value columns into single rows -


i'm trying take key-value combinations , put values on same row keys. i'm pretty sure knew how @ 1 point (i think data.table) , i've been looking @ usual suspects reshape2, tidyr, data.table, etc, can't seem figure out simple solution.

key1 = c(1,1,1,1,2,2,2,2) key2 = c("a","a","b","b","c","c","d","d") value = c("a","b","c","d","e","f","g","h") kvframe = data.frame(key1,key2,value)  #  key1 key2 value #1    1        #2    1        b #3    1    b     c #4    1    b     d #5    2    c     e #6    2    c     f #7    2    d     g #8    2    d     h 

here's table like:

# key1 key2 value1 value2 #    1              b #    1    b      c      d #    2    c      e      f #    2    d      g      h 

most of key1,key2 pairs have same number of corresponding values, not of them do. i'm hoping solution number of value columns equal max number of values given key set, pairs fewer values filled in na.

you need sequence column group 'key1/key2'.

library(data.table) # v1.9.5+ setdt(kvframe)[, seq := paste0('value', 1:.n), = .(key1, key2)] # generate seq dcast(kvframe, key1 + key2  ~seq, value.var = 'value') # cast long wide  #   key1 key2 value1 value2 #1:    1              b #2:    1    b      c      d #3:    2    c      e      f #4:    2    d      g      h 

or using reshape base r

 d1 <- transform(kvframe, seq=ave(seq_along(value),               key1, key2, fun=seq_along))  reshape(d1, idvar=c('key1', 'key2'), timevar='seq', direction='wide')  #  key1 key2 value.1 value.2  #1    1                b  #3    1    b       c       d  #5    2    c       e       f  #7    2    d       g       h 

or

library(tidyr) spread(d1, seq, value) 

Comments

Popular posts from this blog

How to connect android app to App engine -

gcc - MinGW's ld cannot perform PE operations on non PE output file -

php - display validation error message next to the textbox in codeigniter -