Skip to content

Instantly share code, notes, and snippets.

@davetang
Last active September 4, 2015 05:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davetang/173136d800336db5c4f2 to your computer and use it in GitHub Desktop.
Save davetang/173136d800336db5c4f2 to your computer and use it in GitHub Desktop.
Sums the rows and columns of a tab-delimited file
#!/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 = '';
my $i = 1;
open(IN,'<',$infile) || die "Could not open $infile: $!\n";
while(<IN>){
chomp;
# expects header on the first line
if ($. == 1){
$header .= "$_\ttotal";
next;
}
next if /^#/;
next if /^$/;
next if /^\s+/;
my @s = split(/\t/);
for (my $j = 0; $j < scalar(@s); ++$j){
$data->[$i]->[$j] = $s[$j]
}
++$i;
}
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);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment