Search code examples
filelualoadtorch

How to load a table from file in Torch / Lua?


Very simple operation. I have a file that contains a table made of N rows and 6 columns, and I would like to load it in a table in my Torch / Lua script.

The data file looks this way:

chromNameA  startA  endA    chromNameB  startB  endB
chr22   16867980    16868130    chr22   16669675    16678717
chr22   16867980    16868130    chr22   16685348    16701095
chr22   16867980    16868130    chr22   16723869    16739035
chr22   16867980    16868130    chr22   16748016    16750787
chr22   16867980    16868130    chr22   16750788    16755877

And I would like to load it in a table, where for example table[1][2] contains 16867980 and so on.

How could I do it? Thanks


Solution

  • You can use string.match to parse individual line into a table and use io.lines to iterate over lines in the file:

    -- script.lua
    local t, patt = {}, ("(%w+)%s+"):rep(5).."(%w+)"
    for line in io.lines() do
      if not line:find("^chromNameA") then
        table.insert(t, {line:match(patt)})
      end
    end
    print(#t, t[1][1], t[1][6]) -- prints `5 chr22 16678717`
    
    -- file.txt
    chromNameA  startA  endA    chromNameB  startB  endB
    chr22   16867980    16868130    chr22   16669675    16678717
    chr22   16867980    16868130    chr22   16685348    16701095
    chr22   16867980    16868130    chr22   16723869    16739035
    chr22   16867980    16868130    chr22   16748016    16750787
    chr22   16867980    16868130    chr22   16750788    16755877
    
    -- execution: lua script.lua <file.txt
    

    You can then start the script as lua script.lua <file.txt and it should produce a table with the structure you want.