2012-10-30 33 views
1

好奇心如果我能在這裏獲得一些幫助。我是一個perl新手,無法弄清楚如何將下面的代碼轉換爲對我的分析更有用的東西。更改代碼以彙總來自多個文件的值

該代碼目前從用戶提供的數據文件列表中獲取第1列和第4列,並將它們放在一起。

我希望我的代碼對這個代碼生成的「當前輸出」的每一行(見下面)做出第四列值(filea,fileb,filec)的總和。不太清楚如何實現這個...

電流輸出:

filea fileb filec 

entrya | 0 |10.2 | 0 
entryb | 0 | 0.0 | 1  
entryc | 8 | 57.0| 46  

所需的輸出

  sum 
entrya | 10.2 
entryb | 1 
entryc | 111 

當前的代碼如下所示:

main: { 


my %data; 

foreach my $file (@rsem_files) { 

    open (my $fh, $file) or die "Error, cannot open file $file"; 
    my $header = <$fh>; # ignore it 
    while (<$fh>) { 
     chomp; 
     my @x = split(/\t/); 
     my $acc = $x[0]; 
     my $count = $x[4]; 
     $data{$acc}->{$file} = $count; 
    } 
    close $fh; 
} 

my @filenames = @rsem_files; 
foreach my $file (@filenames) { 
    $file = basename($file); 
} 


print join("\t", "", @filenames) . "\n"; 
foreach my $acc (keys %data) { 

    print "$acc"; 

    foreach my $file (@rsem_files) { 

     my $count = $data{$acc}->{$file}; 
     unless (defined $count) { 
      $count = "NA"; 
     } 

     print "\t$count"; 

    } 

    print "\n"; 

} 


exit(0); 
} 
+1

你說第一和第四,但第一列是一個字符串...所以你的意思是你想每列的第2和第4列的值的總和? –

+0

對不起,這是不好的措辭。第一列和第四列來自另一個數據文件。我想將filea fileb和filec的值彙總到一列中。 – jasongallant

+0

List :: Util有一個sum方法,看看那個。 – jshy

回答

1

改變@rsemfiles環:

# create $total variable outside loop 
my $total = 0; 
foreach my $file (@rsem_files) { 
    my $count = $data{$acc}->{$file}; 
    # change unless to if, no need for NA 
    if (defined $count) { 
     $total += $count; 
    } 
} 
# move print outside loop so it happens once instead of per-file 
print '\t$total\n'; 
+0

太棒了,就是這樣!比使用其他庫更好。乾杯! – jasongallant

+0

你是否清楚它做了什麼以及我如何改變它? –

+0

是的,這與我嘗試的方法類似,但由於逃離我的原因,它沒有正確添加東西。我認爲這可能與它在循環中的位置有關。 – jasongallant

0
foreach $line(@rsemfiles) { 
    if ($line=~ /^entry/) { 
    #match the line starting with the word entry 
    my $entry=$1; my $filea=$2; my $fileb=$3; my $filec=$4; 
    # make variables out of the column values 

既然你有這些變量,你可以對它們進行數學運算。