in reply to How to group by a column and calculate max/min on another
It appears that you want to have three lists for each hash key, but your code is intermingling the data into a single list. You could split the lists out by name like this:
push( @{ $gene_hash{$gene_key}{min_start} }, $start ); push( @{ $gene_hash{$gene_key}{max_end} }, $end ); push( @{ $gene_hash{$gene_key}{max_ex} }, $ex );
Then, of course, you'd have to change your report loop a little:
my $Low=min( @ {$gene_hash{$key}{min_start} } ); my $High=max( @ {$gene_hash{$key}{max_end} } ); my $High_ex=max( @ {$gene_hash{$key}{max_ex} } );
However, since your report appears to give only one line per CHR:GENE, I'd suggest doing your data aggregation while reading, rather than trying to do it in your output loop. Also, your data structure uses hardcoded array positions for different data elements, which will be confusing when you change your program. So I'd suggest using a HoH, where the second level of your hash contains the name of the item you're aggregating, something like this (untested):
while (<DATA>) { chomp; my ($chr, $start, $end, $gene, $ex) = split(/\t/, $_); my $gene_key = $chr.":".$gene; my $cur_gene = $gene_hash{$gene_key}; $$cur_gene{min_start} = $start unless $$cur_gene{min_start}<$start +; $$cur_gene{max_end} = $end unless $$cur_gene{max_end}>$end; $$cur_gene{max_ex} = $ex unless $$cur_gene{max_ex}>$ex; $gene_hash{$gene_key} = $cur_gene; }
This code, as it reads each CHR:GENE combination will update the min_start, max_end and max_ex values. This way, at the end of your input loop, you already have the values you want, and you can simply retrieve your values in the output loop like this:
my $Low=$gene_hash{$key}{min_start}; my $High=$gene_hash{$key}{max_end}; my $High_ex=$gene_hash{$key}{max_ex};
...roboticus
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: How to group by a column and calculate max/min on another
by perl_paduan (Initiate) on Aug 03, 2010 at 14:02 UTC |