Unpivoting a table

711 views
Skip to first unread message

Leon Baum

unread,
Dec 23, 2013, 4:47:11 PM12/23/13
to personal...@googlegroups.com

Hi,

Following a post on the wiki, I am able to pivot a table on a given
column, but I am struggling to reverse the operation.

In the example below, I pivot the table "t" on column "x". I then
attempt to take the resulting table, "t2", and unpivot it, but I end up
losing column "x". Is there an elegant solution?

q)t: ([]x: raze 4#' til 3; y: raze 3# enlist `a`b`c`d; z: 12?1f)
q)t
x y z
--------------
0 a 0.5074456
0 b 0.3056222
0 c 0.6886731
0 d 0.2316704
1 a 0.5876646
1 b 0.3976699
1 c 0.3982375
1 d 0.1628311
2 a 0.7589342
2 b 0.8416255
2 c 0.04755326
2 d 0.217142
q)t2: exec (distinct t`y)#y!z by x:x from t
q)t2
x| a b c d
-| ----------------------------------------
0| 0.5074456 0.3056222 0.6886731 0.2316704
1| 0.5876646 0.3976699 0.3982375 0.1628311
2| 0.7589342 0.8416255 0.04755326 0.217142
q)raze {([] y:key x; z:value x)} each t2
y z
------------
a 0.5074456
b 0.3056222
c 0.6886731
d 0.2316704
a 0.5876646
b 0.3976699
c 0.3982375
d 0.1628311
a 0.7589342
b 0.8416255
c 0.04755326
d 0.217142


Thanks,
Leon

Charles Skelton

unread,
Dec 23, 2013, 5:43:20 PM12/23/13
to personal...@googlegroups.com
changing yours just slightly -

q)t~ungroup{`y`z!(key x;value x)}each t2
1b




--
You received this message because you are subscribed to the Google Groups "Kdb+ Personal Developers" group.
To unsubscribe from this group and stop receiving emails from it, send an email to personal-kdbpl...@googlegroups.com.
To post to this group, send email to personal...@googlegroups.com.
Visit this group at http://groups.google.com/group/personal-kdbplus.
For more options, visit https://groups.google.com/groups/opt_out.

Reply all
Reply to author
Forward
0 new messages