2012-09-02 79 views
0

矩陣格式我有數組的數組,其中每個數組是這樣的:如何創建在Perl

clusterA gene1 1 
clusterA gene2 0 
clusterB gene1 1 
clusterB gene2 0 

我想產生這樣一個文件:

name  gene1 gene2 
clusterA 1   0 
clusterB 1   0 

當前的嘗試:

if (condition) { 

    @array = ($cluster, $genes, "1"); 
} 
elsif (not condition) { 

    @array = ($cluster, $genes, "0"); 
} 
push @AoA, [ @array ]; 

@A0A是我的數組數組。

+0

你能澄清你的數組結構嗎? – perreal

+0

請張貼您的嘗試 – Zaid

+0

@perreal問題已更新 – shaq

回答

0

該解決方案不知道基因的名字的時間提前。它將爲所有看到的基因創建列。而且,它使用散列哈希。我解決了類似的問題,並能夠使用解決方案here的一些相同部分。

#!/usr/bin/perl 
use strict; 
use warnings; 

my @array = map [split], split /\n/, <<EOF; 
clusterA gene1 1 
clusterA gene2 0 
clusterB gene1 1 
clusterB gene2 0 
clusterC gene3 9 
EOF 

my %data; 
for my $aref (@array) { 
    $data{$aref->[0]}{$aref->[1]} = $aref->[2]; 
} 

my %seen; 
my @genes = sort 
      grep ! $seen{$_}++, 
      map keys %$_, values %data; 

my $format = "%-15s" . "%-10s" x @genes . "\n"; 

printf $format, 'Cluster', @genes; 

for my $name (sort keys %data) { 
    my $href = $data{$name}; 
    printf $format, $name, map defined $_ ? $_ : 'none', @$href{ @genes }; 
} 

這產生了下面的輸出。

Cluster  gene1  gene2  gene3 
clusterA  1   0   none 
clusterB  1   0   none 
clusterC  none  none  9 

更新:它可能會更容易在首位,而不是陣列的陣列創建哈希的哈希值。像:

my %data; 
$data{$cluster}{$genes} = condition ? 1 : 0; 
+0

夢幻般的偉大答案 – shaq

0
use warnings; 
use strict; 

my @AoA = (['a', 'b', 'c'], ['d', 'e', 'f']); 

open my $outf, ">", "output" 
    or die(); 

print $outf join(" ", qw/name gene1 gene2/), "\n"; 
foreach my $arr (@AoA) { 

    my @data = @{$arr}; 
    print $outf join(" ", @data), "\n"; 
} 
close $outf; 
+0

這不是答案,在這種情況下,「b和」e「應該是矩陣的列,」a「和」d「是行,」c「和」f「分別是對應於行和列的值 – shaq

0
my %HoH; 

foreach my $row (@AoA) 
{ 
    $HoH{$row->[0]}{$row->[1]} = $row->[2]; 
} 

print <<EOF; 
name  gene1 gene2 
clusterA $HoH{clusterA}{gene1}   $HoH{clusterA}{gene2} 
clusterB $HoH{clusterB}{gene1}   $HoH{clusterB}{gene2} 
EOF 
+0

它是難以理解你的新手代碼! –

+0

@fxzuz:我已經明確了一點,不知道除了[perldsc](http://perldoc.perl.org/perldsc.html# HASHES-OF-HASHES)和[perlop](http://perldoc.perl.org/perlop.html#%3c%3cEOF)。TBH沒有太多的理解,我沒有提供「自學Perl」服務 – Oktalist

0

難道奧尼爾想要總額是多少?如果是這樣的回答會更喜歡(留下所有的文件I/O出簡化測試):

my @AOA = (
    [ qw(clusterA gene1 1) ], 
    [ qw(clusterA gene2 0) ], 
    [ qw(clusterB gene1 1) ], 
    [ qw(clusterB gene2 0) ], 
); 

my %clusters; 
my @genes = (0, 0); 

foreach my $array (@AOA) { 

    my ($cluster, $gene, $value) = @$array; 
    if ($gene =~ /^gene(\d+)$/) { 

     my $v = $1; 
     $clusters{$cluster} = [ 0, 0 ] 
        unless (exists $clusters{$cluster}); 
     $clusters{$cluster}->[$v-1] += $value; 
    } 
} 

my $format = '%-12s %6s %6s'."\n"; 
printf($format, qw(name gene1 gene2)); 

foreach my $cluster (sort keys %clusters) { 

    printf $format, $cluster, @{ $clusters{$cluster} }; 
}