Hi there
I have been trying to do the following
Taking 'ob1' as the 'object of interest' I have a text file which looks like this
ob1, ob2, 34
ob1, ob3, 56
ob1, ob4, 12
ob1, ob5, 78
ob1, ob6, 23
ob3, ob1, 56
ob7, ob1, 23
ob8, ob1, 12
ob9, ob1, 90
etc ...
and what I need is to create a matrix like this
ob1 ob2 ob3 ob4 ob5 ob6 ob7 ob8 ob9
ob1 0 34 56 12 78 23 23 12 90
ob2 34
ob3 56
ob4 12
ob5 78
ob6 23
ob7 23
ob8 12
ob9 90
And for any 'duplicate results' like these
ob1, ob3, 56
ob3, ob1, 56
Only take the first instance (as the result is the same, regardless of the direction).
Ob2 then becomes the 'object of interest' and column two and row two is populated in the same way (but with different values potentially) as the first column and first row was populated with ob1 was the 'object if interest'. And the ob3 becomes the 'object of interest' until the matrix is completely filled. In some cases, there may be some missing values (for example there may not be a 'ob4 ob5' value and I need to take that into account - perhaps by printing 'NULL' or something).
I asked for help from Perl Monks yesterday and this is the code I have so far
#!/usr/local/bin/perl
use strict;
my $data = $ARGV[0];
# open file here
open(DATA, "$data") || die "cant open file for reading\n";
my %table;
my %rows;
my %cols;
for(<DATA>) {
my($row,$col,$val) = split ',';
$table{$row}{$col} = $val;
$rows{$row}++;
$cols{$col}++;
}
for my $col (sort keys %cols) {
print "\t$col";
}
print "\n";
for my $row (sort keys %rows) {
print "$row\t";
for my $col (sort keys %cols) {
print $table{$row}{$col} if defined $table{$row}{$col};
print "\t";
}
print "\n";
}
The results I get using the code above is:
ob1 ob2 ob3 ob4 ob5 ob6
ob1 34
56
12
78
23
ob3 56
ob7 23
ob8 12
ob9 90
Which isn't quite what I need, but I don't know how to fix it (due to my blind spot regarding hashes I suspect).
Any suggestions much appreciated.
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.