0

I have a table i want to update:

q)show table:([]letter:`a`b`c`a;fruit:`apple`banana`pear`strawberry;family:`mom`dad`brother`sister)
letter fruit      family
-------------------------
a      apple      mom
b      banana     dad
c      pear       brother
a      strawberry sister

I want to replace all entries with the name of their respective column.

This seems to work:

q){![table;();0b;(enlist x)!(enlist `x)]}`letter
letter fruit      family
-------------------------
letter apple      mom
letter banana     dad
letter pear       brother
letter strawberry sister

...but not this:

q){![table;();0b;(enlist x)!(enlist `x)]}`letter`fruit
'type
  [1]  {![table;();0b;(enlist x)!(enlist `x)]}
        ^
q))

The purpose is to create a function that creates dummy variables for categorical variables, so I need a general function. Any suggestions?

2 Answers2

3

This can be achieved with @ apply instead of a functional update like so:

q){@[`table;x;:;x]}`letter`fruit
`table
q)table
letter fruit family
--------------------
letter fruit mom
letter fruit dad
letter fruit brother
letter fruit sister

Edit - For all cols:

{@[`table;x;:;x]} each cols table

or

{@[x;y;:;y]}/[table;cols table]

q)table
letter fruit family
-------------------
letter fruit family
letter fruit family
letter fruit family
letter fruit family
Matt Moore
  • 2,705
  • 6
  • 13
  • I need a generalization, useable for any table without plugging in specific column names. is there a way to make this work? {@[`table;x;:;x]}cols table – Grant Baker Dec 13 '20 at 02:14
2

Your original functional update could work like this:

q){![table;();0b;x!enlist'[x:(),x]]}cols table
letter fruit family
-------------------
letter fruit family
letter fruit family
letter fruit family
letter fruit family
terrylynch
  • 11,844
  • 13
  • 21