本文介绍了如何使用awk计算趋势?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个温度数据的时间序列:
I have a time series of temperature data as:
ifile.txt
1921 25
1922 25.1
1923 24.2
1924 23.4
1925 24.4
1926 25.1
1927 23.6
1928 25.2
1929 23.9
1930 25.6
我想计算1923-1929年期间的趋势.
I would like to compute the trend for the period 1923-1929.
我的算法是:
使以上几点适合诸如
Y = mX + c ; where m is the trend
我可以找到整个时期的趋势,但是在选择特定时期时我无法修改脚本.您能检查一下我的脚本吗?
I could find the trend for whole period, but I can't able to modify my script when selecting for a specific period. Would you please check my script?
awk '/1923/,/1929/ {if (NR==FNR) x[NR] = $1;y[NR] = $2;
sx += x[NR]; sy += y[NR];
sxx += x[NR]*x[NR];
sxy += x[NR]*y[NR];}
END{
det = NR*sxx - sx*sx;
trend = (NR*sxy - sx*sy)/det;
print trend;}' ifile.txt
它没有打印正确的值.
It is not printing correct value.
The correct value is 0.0679
推荐答案
您可以稍微简化一下,您无需计算匹配记录. NR
将是END块中的总行数.
you can simplify it little bit, you're not counting the matching records. NR
will be total number of lines in the END block.
awk '/1923/,/1929/ {sx+=$1; sy+=$2; c++;
sxx+=$1*$1; sxy+=$1*$2}
END {det=c*sxx-sx*sx;
print det?(c*sxy-sx*sy)/det:"DIV0"}' file
还需要考虑分母为零.趋势出现
also need to consider denominator being zero. The trend comes up as
0.0678571
这篇关于如何使用awk计算趋势?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!