Question

What I essentially want to do is take a table like this one, where the top row contains columns names:

A    B    B    B
a    9    8    9
a    6    5    3
b    4    4    5
b    8    3    4

and merge the columns with the same names while keeping the corresponding row names (contained in the first column) like so:

A    B
a    9
a    8
a    9
a    6
a    5
a    3
b    4
b    4
b    5
b    8
b    3
b    4

Any help would be appreciated.

Was it helpful?

Solution

What you are trying to do is 'melt' a table. I've used a library for this in R but not in Perl. There is a Perl module called Data::Table which does have a melt function for multidimensional lists.

OTHER TIPS

You can visualize your initial table (T1) as:

0    1    2    3
A    B    B    B
a    9    8    9
...

where you have columns 0 .. 3. Each time you print the lines of your transformed table (T2), you'll be printing column 0. So T1's line 1 ("top row") would be the following line 1 of T2:

0    1

T1's line 2 would be the following three lines of T2:

0    1
0    2
0    3

Each of T1's lines, from line 2 to its last line, will transform into three lines of T2--in the pattern shown above.

Psudocode:

  1. Get a line of T1
  2. split the line into its elements
  3. Is it line 1 ("top row") of T1? If so, print elements 0 and 1 with a newline. Go to step 1.
  4. It's not line 1 of T1. Print the following, each on its own line: elements 0 and 1, elements 0 and 2, elements 0 and 3.
  5. Go to step 1.

When a file or DATA is being read using while, how can you get the current line number? Perl uses $. to store that information. So if $. == 1, it's line 1.

Hope this helps!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top