Advertisement
Guest User

Untitled

a guest
Sep 3rd, 2015
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.31 KB | None | 0 0
  1. #!/usr/bin/env perl
  2.  
  3. #
  4. # Reads a tab-delimited file with column and row names
  5. # sums the rows and columns and outputs a tab-delimited
  6. # file with an extra row and column for the sums
  7. #
  8.  
  9. use strict;
  10. use warnings;
  11.  
  12. my $usage = "Usage: $0 <infile.tsv>\n";
  13. my $infile = shift or die $usage;
  14.  
  15. my $data = [];
  16. my $header = '';
  17.  
  18. open(IN,'<',$infile) || die "Could not open $infile: $!\n";
  19. while(<IN>){
  20. chomp;
  21. # expects header
  22. if ($. == 1){
  23. $header .= "$_\ttotal";
  24. next;
  25. }
  26. my @s = split(/\t/);
  27. my $i = $. - 1;
  28. for (my $j = 0; $j < scalar(@s); ++$j){
  29. $data->[$i]->[$j] = $s[$j]
  30. }
  31. }
  32. close(IN);
  33.  
  34. # variables for storing the column sums
  35. my @col_sum = ();
  36. my $last_col_sum = 0;
  37.  
  38. # print the header
  39. print "$header\n";
  40.  
  41. # expects header, skipping first row
  42. for (my $r=1; $r < scalar(@$data); ++$r){
  43. my $row_sum = 0;
  44. my $row = "$data->[$r]->[0]\t";
  45. # expects row names, skipping first column
  46. for (my $c=1; $c < scalar(@{$data->[$r]}); ++$c){
  47. $row .= "$data->[$r]->[$c]\t";
  48. $row_sum += $data->[$r]->[$c];
  49.  
  50. # column sum
  51. $col_sum[$c] += $data->[$r]->[$c];
  52. }
  53. print "$row$row_sum\n";
  54. $last_col_sum += $row_sum;
  55. }
  56.  
  57. my $col_sum_row = "total\t";
  58. for (my $c = 1; $c < scalar(@col_sum); ++$c){
  59. $col_sum_row .= "$col_sum[$c]\t";
  60. }
  61.  
  62. print "$col_sum_row$last_col_sum\n";
  63.  
  64. exit(0);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement