3

I have two files: the first one contains lines where the first column is an ID, and the remaining columns are votes, e.g.

3242 -1 1 -1 1 1 1

In a first step I want to calculate the majority for the IDs. For the example above, the vote is 1 (since there are more positive votes then negative ones). I would like to store the results in an output file with lines such as

3242 1

I also have a file that contains the 'weights' of the respective votes, e.g.

3242 0.9 0.1 0.9 0.2 0.1 0.2

In a second step, I also want to calculate the weighted votes for the different lines. In this case this would be

(0.9 * -1) + (0.1 * 1) + (0.9 * -1) + (0.2 * 1) + (0.1 * 1) + (0.2 * 1) = -1.2

The result is negative, so the vote should be -1. Again, I would like to store this in an output file, where each line contains the ID and the resulting vote.

Would this be possible with awk, perl,...?

1 Answer 1

1
#!/usr/bin/perl

use List::MoreUtils qw(pairwise);
use List::Util qw(sum);
use strict;

sub read_file {
    my ($filename) = @_;
    open F, '<', $filename or die "Could not open $filename: $!";
    my %data;
    while (<F>) {
        my ($id, @data) = split;
        $data{$id} = \@data;
    }
    close F;
    return %data;
}

sub output_file {
    my ($filename, %data) = @_;
    open F, '>', $filename or die "Could not open $filename: $!";
    for (sort keys %data) {
        print F "$_\t$data{$_}\n";
    }
    close F;
}

my %votes = read_file 'votes.tsv';
my %weights = read_file 'weights.tsv';

my %unweighted;
while (my ($id, $data) = each(%votes)) {
    my $sum = List::Util::sum(@$data);
    $unweighted{$id} = $sum < 0 ? -1 :
                       $sum > 0 ? +1 : 0;
}
output_file('unweighted.tsv', %unweighted);

my %weighted;
while (my ($id, $data) = each(%weights)) {
    my $dot_prod = sum(pairwise { $a * $b } @{$votes{$id}}, @$data);
    $weighted{$id} = $dot_prod < 0 ? -1 :
                     $dot_prod > 0 ? +1 : 0;
}
output_file('weighted.tsv', %weighted);

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .