Search code examples
j

How can I manipulate/extract info from the following table in J


   ]data=:_3 ]\ 'Jack';23;178;'Rick';27;181;'Alice';41;178;'Mitch';31;184;'Paul';32;179
┌─────┬──┬───┐
│Jack │23│178│
├─────┼──┼───┤
│Rick │27│181│
├─────┼──┼───┤
│Alice│41│178│
├─────┼──┼───┤
│Mitch│31│184│
├─────┼──┼───┤
│Paul │32│179│
└─────┴──┴───┘

The first field is name, second is age and third is height in cm.


Solution

  • If you search for [j] table you'll find this question that yours is arguably a duplicate of, but it's easy to imagine that its answer wouldn't seem to apply to your data, so I've adapted the answer below:

       NB. Select names
       0 {"1 data
    +----+----+-----+-----+----+
    |Jack|Rick|Alice|Mitch|Paul|
    +----+----+-----+-----+----+
       
       NB. test if name contains a 'k'
       +/"1 'k' e.~ 0 {::"1 data
    1 1 0 0 0
       
       NB. select rows where the name contains a 'k'
       (+/"1 'k' e.~ 0 {::"1 data) # data
    +----+--+---+
    |Jack|23|178|
    +----+--+---+
    |Rick|27|181|
    +----+--+---+
       (#~ [: +/"1 'k' e.~ 0&{::"1) data
    +----+--+---+
    |Jack|23|178|
    +----+--+---+
    |Rick|27|181|
    +----+--+---+
       
       NB. select names where height > 180
       > 0{"1 (#~ 180 < 2&{::"1) data
    Rick 
    Mitch
       
       NB. get average age and height
       (+/%#) 1 2 pick"1 data
    30.8 180
       
       NB. add a row
       is =: 4 : 'data =: data, (<x),y'
       years =: 1 : '<u'
       cm =: 1 : '<u'
       'Rebecca' is 24 years, 176 cm
    ... omitted ...
       'Gregory' is 37 years, 182 cm
    ... omitted ...
       load 'inverted'
       ,.&.> ifa data
    +-------+--+---+
    |Jack   |23|178|
    |Rick   |27|181|
    |Alice  |41|178|
    |Mitch  |31|184|
    |Paul   |32|179|
    |Rebecca|24|176|
    |Gregory|37|182|
    +-------+--+---+
    

    That last bit is from Inverted Tables, which has some advantages, probably the very least of which is that they echo less noisily.