Dr.Ruud wrote:
On 2011-01-08 03:16, S.F. wrote:

I have a data file with n columns and r row.
The first 3 columns and the first 5 rows are:

2 3 1
1 6 X
4 0 X
X 8 X
5 X 5

The "X" means missing.
How could I write a script to calculate the average by column and
replace "X" with the average?

The output should be like:

2 3 1
1 6 3
4 0 3
3 8 3
5 4.25 5

perl -MData::Dumper -ale'
@d=map[...@t=split;$n=$s=0;$n++,$s+=$_ for grep$_ ne"X",@t;$_=$s/$n for
grep$_ eq"X",@t;@t}],split",",$ARGV[0];
print dump...@d
' "2 1 4 X 5,3 6 0 8 X,1 X X X 5"

Why the do{} block? Just use map's block. And why include the -a switch when you are not using @F? And you don't really need the -l switch either because Data::Dumper already provides its own newlines.

perl -MData::Dumper -e'
@d=map...@t=split;$n=$s=0;!/X/and$n++,$s+=$_ f...@t;/X/and$_=$s/$n f...@t;\...@t}split/,/,$ARGV[0];
  print dump...@d
' "2 1 4 X 5,3 6 0 8 X,1 X X X 5"



John
--
Any intelligent fool can make things bigger and
more complex... It takes a touch of genius -
and a lot of courage to move in the opposite
direction.                   -- Albert Einstein

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to