AWK-Get total count of records for numerical grouped column - awk

I have a variable which splits the results of a column based on a condition (group by in others programming languages).
I'm trying to have a variable that counts the NR of each group. If we sum all the groups we should have the NR of the file.
When I try to use NR in the calculation for example NR[variable that splits], I get a fatal error "you tried to use scalar as matrix.
Any ideas how to use NR as a variable, but not counting all the records, only those from each group?
sex, weight
male,50
female,49
female,48
male,66
male,78
female,98
male,74
male,54
female,65
In this case the NR would be 9 BUT, in reality I want a way to get that NR of male is 5 and 4 for female.
I have the total sum of weigth column but struggle to get the avg:
sex= $(f["sex"])
ccWeight[sex] += $(f["weight"])
avgWeight = ccWeight[sex] / ¿?
Important: I don't need to print the result as of now, just to store this number on a variable.

One awk idea:
awk -F, '
NR>1 { counts[$1]++ # keep count of each distinct sex
counts_total++ # replace dependency on NR
weight[$1]+=$2 # keep sum of weights by sex
}
END { for (i in counts) {
printf "%s: (count) %s of %s (%.2f%)\n",i,counts[i],counts_total,(counts[i]/counts_total*100)
printf "%s: (avg weight) %.2f ( %s / %s )\n",i,(weight[i]/counts[i]),weight[i],counts[i]
}
}
' sample.dat
NOTE:
OP can add additional code to verify total counts and weights are not zero (so as to keep from generating a 'divide by zero' error)
perhaps print a different message if there are no (fe)male records to process?
This generates:
female: (count) 4 of 9 (44.44%)
female: (avg weight) 65.00 ( 260 / 4 )
male: (count) 5 of 9 (55.56%)
male: (avg weight) 64.40 ( 322 / 5 )

GNU datamash might be what you are looking for, e.g.:
<infile datamash -Hst, groupby 1 count 1 sum 2 mean 2 | column -s, -t
Output:
GroupBy(sex) count(sex) sum(weight) mean(weight)
female 4 260 65
male 5 322 64.4

Related

How to calculate average per row (awk command)

I have a file with 269 countries.
10 columns each country.
I need to create a script that will average calculation of Japan from the 5-10 column and save the average in a new file
like :
Japan,JPN,Forest area (% of land area)= "(The average number)".
My file is. Csv
I don't need all the country average. I just want to calculate average of Japan.
Jordan,JOR,Forest area (% of land area),AG.LND.FRST.ZS,1.0982203199,1.0982203199,1.0982203199,1.0982203199,1.0982203199,1.0982203199,,
Japan,JPN,Forest area (% of land area),AG.LND.FRST.ZS,68.4844328624,68.4791046618,68.4737766074,68.4693877551,68.4649989028,68.4606100505,,
Kazakhstan,KAZ,Forest area (% of land area),AG.LND.FRST.ZS,1.2256917435,1.2256917435,1.2256917435,1.2256917435,1.2256917435,1.2256917435,,
Solution:
awk -v country=Japan 'BEGIN{FS=","}{ if( $1==country ) { n=0; for(i=5;i<NF;++i) { if( $i ) { ++n; sum += $i; } } print country ": " sum/n; }}' infile.txt
Variable country can be set at wish. The fields from 6 to end are summed up and divided by the number of entries to get the avarage.

Reading fields in previous lines for moving average

Main Question
What is the correct syntax for recursively calling AWK inside of another AWK program, and then saving the output to a (numeric) variable?
I want to call AWK using 2/3 variables:
N -> Can be read from Bash or from container AWK script.
Linenum -> Read from container AWK program
J -> Field that I would like to read
This is my attempt.
Container AWk program:
BEGIN {}
{
...
# Loop in j
...
k=NR
# Call to other instance of AWK
var=(awk -f -v n="$n_steps" linenum=k input-file 'linenum-n {printf "%5.4E", $j}'
...
}
END{}
Background for more general questions:
I have a file for which I would like to calculate a moving average of n (for example 2280) steps.
Ideally, for the first n rows the average is of the values 1 to k,
where k <= n.
For rows k > n the average would be of the last n values.
I will eventually execute the code in many large files, with several columns, and thousands to millions of rows, so I'm interested in streamlining the code as much as possible.
Code Excerpt and Description
The code I'm trying to develop looks something like this:
NR>1
{
# Loop over fields
for (j in columns)
{
# Rows before full moving average is done
if ( $1 <= n )
{
cumsum[j]=cumsum[j]+$j #Cumulative sum
$j=cumsum[j]/$1 # Average
}
#moving average
if ( $1 > n )
{
k=NR
last[j]=(awk -f -v n="$n_steps" ln=k input-file 'ln-n {printf "%5.4E", $j}') # Obtain value that will get ubstracted from moving average
cumsum[j]=cumsum[j]+$j-last[j] # Cumulative sum adds last step and deleted unwanted value
$j=cumsum[j]/n # Moving average
}
}
}
My input file contains several columns. The first column contains the row number, and the other columns contain values.
For the cumulative sum of the moving average: If I am in row k, I want to add it to the cumulative sum, but also start subtracting the first value that I don't need (k-n).
I don't want to have to create an array of cumulative sums for the last steps, because I feel it could impact performance. I prefer to directly select the values that I want to substract.
For that I need to call AWK once again (but on a different line). I attempt to do it in this line:
k=NR
last[j]=(awk -f -v n="$n_steps" ln=k input-file 'ln-n {printf "%5.4E", $j}'
I am sure that this code cannot be correct.
Discussion Questions
What is the best way to obtain information about a field in a previous line to the one that AWK is working on? Can it be then saved into a variable?
Is this recursive use of AWK allowed or even recommended?
If not, what could be the most efficient way to update the cumulative sum values so that I get an efficient enough code?
Sample input and Output
Here is a sample of the input (second column) and the desired output (third column). I'm using 3 as the number of averaging steps (n)
N VAL AVG_VAL
1 1 1
2 2 1.5
3 3 2
4 4 3
5 5 4
6 6 5
7 7 6
8 8 7
9 9 8
10 10 9
11 11 10
12 12 11
13 13 12
14 14 13
14 15 14
If you want to do a running average of a single column, you can do it this way:
BEGIN{n=2280; c=7}
{ s += $c - a[NR%n]; a[NR%n] = $c }
{ print $0, s /(NR < n : NR ? n) }
Here we store the last n values in an array a and keep track of the cumulative sum s. Every time we update the sum we correct by first removing the last value from it.
If you want to do this for a couple of columns, you have to be a bit handy with keeping track of your arrays
BEGIN{n=2280; c[0]=7; c[1]=8; c[2]=9}
{ for(i in c) { s[i] += $c[i] - a[n*i + NR%n]; a[n*i + NR%n] = $c[i] } }
{ printf $0
for(i=0;i<length(c);++i) printf OFS (s[i]/(NR < n : NR ? n))
printf ORS
}
However, you mentioned that you have to add millions of entries. That is where it becomes a bit more tricky. Summing a lot of values will introduce numeric errors as you loose precision bit by bit (when you add floats). So in this case, I would suggest implementing the Kahan summation.
For a single column you get:
BEGIN{n=2280; c=7}
{ y = $c - a[NR%n] - k; t = s + y; k = (t - s) - y; s = t; a[NR%n] = $c }
{ print $0, s /(NR < n : NR ? n) }
or a bit more expanded as:
BEGIN{n=2280; c=7}
{ y = $c - k; t = s + y; k = (t - s) - y; s = t; }
{ y = -a[NR%n] - k; t = s + y; k = (t - s) - y; s = t; }
{ a[NR%n] = $c }
{ print $0, s /(NR < n : NR ? n) }
For a multi-column problem, it is now straightforward to adjust the above script. All you need to know is that y and t are temporary values and k is the compensation term which needs to be stored in memory.

combine specific output and display in specific header

I am trying to combine all matching text before the left of the | and output that to the column "Gene". The amount of lines in the match are outputted to the "Targets" column, the average of $3 to the "Average Depth" column, along with the average of the #'s to the right of the = to the " Average GC" column. I am having some trouble in doing this and need some expert help. Thank you :).
input
chr10:79793602-79793721 RPS24|gc=59.7 150.3
chr10:79795083-79795202 RPS24|gc=41.2 111.4
chr10:79797665-79797784 RPS24|gc=37 69.8
chr11:119077113-119077232 CBL|gc=67.9 27.3
chr11:119103143-119103420 CBL|gc=41.9 240.3
chr11:119142430-119142606 CBL|gc=42.6 177.1
chr11:119144563-119144749 CBL|gc=46.2 324.4
current output
Gene TargetsAverage DepthAverage GC
gc 803 0.0 0.0
desired output
ID times depth GC
RPS24 3 110.5 46.0
CBL 4 192.3 49.7
awk
awk -F'[ |=]' '
{
id[$2] += $4
value[$2] += $5
occur[$2]++
}
END{
printf "%-8s%8s%8s%8s\n", "Gene", "Targets", "Average Depth", "Average GC"
for (i in id)
printf "%-8s%8d%8.1f%8.1f\n", i, occur[i],value[i]/occur[i],id[i]/occur[i]
}' input
#Chris - Your editing of the question has not been very helpful, but I can confirm that, except for the first printf statement, the program runs as expected, which is in accordance with the "desired output". I have used three different awks; the only difference between the outputs is (as expected) the ordering of the rows. You may have to be more specific about the version of awk you are using.
Solution in TXR:
$ txr table2.txr data
ID times depth GC
RPS24 3 110.5 46.0
CBL 4 192.3 49.7
Code in table2.txr:
#(output)
ID times depth GC
#(end)
#(repeat)
# (all)
#nil:#nil-#nil #id|#nil
# (and)
# (collect :gap 0)
#nil:#nil-#nil #id|gc=#gc #dep
# (set (gc dep) (#(tofloat gc) #(tofloat dep)))
# (end)
# (bind n #(length gc))
# (bind avg-gc #(format nil "~,1f"
(/ [reduce-left + gc] n)))
# (bind avg-dep #(format nil "~,1f"
(/ [reduce-left + dep] n)))
# (output)
#{id 9} #{n 6} #{avg-dep 13} #{avg-gc}
# (end)
# (end)
#(end)
What lumps together the entries with the same ID is the two parallel branches of the all directive. The first branch loosely matches the pattern of a single line, extracting the ID, binding it to the id variable. This variable is visible to the second branch, where its appearance introduces a back-referencing constraint. Here, multiple consecutive (:gap 0) lines are matched at the same position (thus including the one which was matched in the first branch of the all). Only lines with the matching id are processed; the collect ends when a non-matching id is encountered (due to the :gap 0 constraint) or when the input ends.

awk to print out lines for cumulative sum

I want to print out lines of a file until the cumulative sum of the third field is greater than 0.99, then print out only the first line for which the cumulative sum is greater than or equal to 0.99. However, if field 2 of the first line for which cumulative sum of field 3 is greater than or equal to 0.99 matches field 2 of the next line, then both lines should be printed.
My file looks like:
rs76832595 -4.4524 0.501109
rs74660964 -4.9815 0.49886
rs12992037 -4.9815 9.8159e-06
rs934367 -4.3376 3.06953e-06
Desired output:
rs76832595 -4.4524 0.501109
rs74660964 -4.9815 0.49886
rs12992037 -4.9815 9.8159e-06
In the above example, the cumulative sum of field 3 exceeds 0.99 at line 2, but I print line 3 as well since field 2 of lines 2 and 3 are equal. If these fields had not been equal, I would print out lines 1 and 2 only.
I have the following command, which works for the cumulative sum, but not for comparing field 2 between adjacent lines:
awk '{sum+=$3;print $0;if(sum>=0.99)exit}' file
Can someone modify this to incorporate the above requirements?
The following should work according to your specifications:
Given file containing
rs76832595 -4.4524 0.501109
rs74660964 -4.9815 0.49886
rs12992037 -4.9815 9.8159e-06
rs934367 -4.3376 3.06953e-06
The following awk-script
awk '{sum+=$3; print $0; if(sum >= 0.99 && prev_row == $2)exit;prev_row=$2}' file
will produce
rs76832595 -4.4524 0.501109
rs74660964 -4.9815 0.49886
rs12992037 -4.9815 9.8159e-06
The change in the script consisted of adding a prev_row=$2 at the end of the statement to keep track of the previous row, and incorporating prev_row into the if-statement.

How to do multi-row calculations using awk on a large file

I have a big file that is sorted on the first word. I need to add a new column for each line with the proportional value: line value/total value for that group; group is determined by the first column. In the below example, the total of group "a" = 100 and hence each line gets a proportion. The total of group "the" is 1000 and hence each line gets the proprotion value of the total of that group.
I need an awk script to do this.
Sample File:
a lot 10
a few 20
a great 20
a little 40
a good 10
the best 250
the dog 750
zisty cool 20
Output:
a lot 10 0.1
a few 20 0.2
a great 20 0.1
a little 40 0.4
a good 10 0.1
the best 25 .25
the dog 75 .75
zisty cool 20 1
You describe this as a "big file." Consequently, this solution tries to save memory: it holds no more than one group in memory at a time. When we are done with that group, we print it out before starting on the next group:
$ awk -v i=0 'NR==1{name=$1} $1==name{a[i]=$0;b[i++]=$3;tot+=$3+0;next} {for (j=0;j<i;j++){print a[j],b[j]/tot} name=$1;a[0]=$0;tot=b[0]=$3;i=1} END{for (j=0;j<i;j++){print a[j],b[j]/tot}}' file
a lot 10 0.1
a few 20 0.2
a great 20 0.2
a little 40 0.4
a good 10 0.1
the best 250 0.25
the dog 750 0.75
zisty cool 20 1
How it works
-v i=0
This initializes the variable i to zero.
NR==1{name=$1}
For the first line, set the variable name to the first field, $1. This is the name of the group.
$1==name {a[i]=$0; b[i++]=$3; tot+=$3+0; next}
If the first field matches name, then save the whole line into array a and save the value of column (field) three into array b. Increment the variable tot by the value of the third field. Then, skip the rest of the commands and jump to the next line.
for (j=0;j<i;j++){print a[j],b[j]/tot} name=$1;a[0]=$0;tot=b[0]=$3;i=1
If we get to this line, then we are at the start of a new group. Print out all the values for the old group and initialize the variables for the start of the next group.
END{for (j=0;j<i;j++){print a[j],b[j]/tot}}
After we get to the last line, print out what we have for the last group.
awk '{a[$1]+=$3; b[i++]=$0; c[j++]=$1; d[k++]=$3} END{for(i=0;i<NR;i++) {print b[i], d[i]/a[c[i]]}}' File
Example:
sdlcb#Goofy-Gen:~/AMD$ cat ff
a lot 10
a few 20
a great 20
a little 40
a good 10
the best 250
the dog 750
zisty cool 20
sdlcb#Goofy-Gen:~/AMD$ awk '{a[$1]+=$3; b[i++]=$0; c[j++]=$1; d[k++]=$3} END{for(i=0;i<NR;i++) {print b[i], d[i]/a[c[i]]}}' ff
a lot 10 0.1
a few 20 0.2
a great 20 0.2
a little 40 0.4
a good 10 0.1
the best 250 0.25
the dog 750 0.75
zisty cool 20 1
Logic: update an array (a[]) with first column as index for each line. save array b[] with complete line for each line, to be used in the end for printing. similarly, update arrays c[] and d[] with first and third column values for each line. at the end, use these arrays to get the results using a for loop, looping through all the lines processed. First printing the line as itself, then the proportion value.