Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env perl
- #
- # Reads a tab-delimited file with column and row names
- # sums the rows and columns and outputs a tab-delimited
- # file with an extra row and column for the sums
- #
- use strict;
- use warnings;
- my $usage = "Usage: $0 <infile.tsv>\n";
- my $infile = shift or die $usage;
- my $data = [];
- my $header = '';
- open(IN,'<',$infile) || die "Could not open $infile: $!\n";
- while(<IN>){
- chomp;
- # expects header
- if ($. == 1){
- $header .= "$_\ttotal";
- next;
- }
- my @s = split(/\t/);
- my $i = $. - 1;
- for (my $j = 0; $j < scalar(@s); ++$j){
- $data->[$i]->[$j] = $s[$j]
- }
- }
- close(IN);
- # variables for storing the column sums
- my @col_sum = ();
- my $last_col_sum = 0;
- # print the header
- print "$header\n";
- # expects header, skipping first row
- for (my $r=1; $r < scalar(@$data); ++$r){
- my $row_sum = 0;
- my $row = "$data->[$r]->[0]\t";
- # expects row names, skipping first column
- for (my $c=1; $c < scalar(@{$data->[$r]}); ++$c){
- $row .= "$data->[$r]->[$c]\t";
- $row_sum += $data->[$r]->[$c];
- # column sum
- $col_sum[$c] += $data->[$r]->[$c];
- }
- print "$row$row_sum\n";
- $last_col_sum += $row_sum;
- }
- my $col_sum_row = "total\t";
- for (my $c = 1; $c < scalar(@col_sum); ++$c){
- $col_sum_row .= "$col_sum[$c]\t";
- }
- print "$col_sum_row$last_col_sum\n";
- exit(0);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement