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.
Perl: Merging columns with the same names and keeping row names
-
06-10-2022 - |
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.
Solution
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:
- Get a line of T1
- split the line into its elements
- Is it line 1 ("top row") of T1? If so, print elements
0
and1
with a newline. Go to step 1. - It's not line 1 of T1. Print the following, each on its own line: elements
0
and1
, elements0
and2
, elements0
and3
. - 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!