3개 열마다 모든 행의 평균을 구합니다.

3개 열마다 모든 행의 평균을 구합니다.

우분투 14.04를 사용하고 있습니다. 탭으로 구분된 파일이 있는 경우:

예 필드필드2 필드3 필드4 필드5 필드6 필드7 필드8 필드9 필드10 필드11 필드12

표본 1 1 2 3 4 5 6 7 8 9 10 11 12

모든 행(각각 3개 열)의 열 평균을 인쇄하고 싶습니다. 출력은 다음과 같습니다.

예시 fieldsField2 Field3 Field4

표본 2 5 8 11

미리 감사드립니다!

답변1

나는 이것을 다음과 같이 해결할 것입니다 :

#!/usr/bin/perl

use warnings;
use strict;

my $field_count = 3;

#discard first row, as the fields don't match
my $first_row = <>;
#iterate STDIN or files specified on command line, just like grep or sed do. 
while ( <> ) {
   #extract the name and values. Maybe you need a 'chomp' to remove linefeeds 
   #it works given your sample data, because the last field is a number. 
   my ( $samplename, @fields ) = split; 
   my @new_fields; 
   while ( @fields ) {
      #extract fields 3 at a time.  
      my @group = splice @fields, 0, $field_count;
      #sum them
      my $sum = 0;
      $sum += $_ for @group;

      my $avg = $sum / @group; #divide by number of elements in this group, so it'll work if there's 1 or 2 'trailing'. 
      #stash that in the new field list. 
      push @new_fields, $avg;
   }
   #print the output line. 
   print join "\t", $samplename, @new_fields,"\n"
}

답변2

A1 Perl: 모든 라인에 레거시 사용

입력 형식 가정: SampleId, 3개 값 그룹

perl -nE '($out,@g)=split;                   #sampleId a1 b1 c1  a2 b2 c2 ...
          while(($a,$b,$c,@g)=@g){           
             $out .= " ".($a+$b+$c)/3 }
          say $out '

또는

A2 Perl: 정규식을 사용하여 대체 및 평가

perl -pe 's!\b(\d+)\s+(\d+)\s+(\d+)! ($1+$2+$3)/3 !ge'

관련 정보