gpt4 book ai didi

awk - 将百分比添加到制表符分隔文本中的列

转载 作者:行者123 更新时间:2023-12-04 16:09:49 24 4
gpt4 key购买 nike

如果前面有多个列,如何添加此百分比列

如下图

Ref Alt Ref_count   Alt_Count   Per (%) Func    Ge
TGA T 2 2 ab PRKCZ
TGA c 6 6 ab PRKCZ
TGA C 8 7 ab PRKCZ
TGA T 9 3 ab PRKCZ
TGA C 9 3 ab PRKCZ
TGA T 9 3 ab PRKCZ
TGA C 9 5 ab PRKCZ
TGA T 9 3 ab PRKCZ
TGA C 5 2 ab PRKCZ
TGA T 4 3 ab PRKCZ

并计算第 4 列占第 3 列的百分比。保持其他列和标题不变

输出应该是这样的

Ref Alt Ref_count   Alt_Count   Per (%) Func    Ge
TGA T 2 2 100.00% ab PRKCZ
TGA c 6 6 100.00% ab PRKCZ
TGA C 8 7 87.50% ab PRKCZ
TGA T 9 3 33.33% ab PRKCZ
TGA C 9 3 33.33% ab PRKCZ
TGA T 9 3 33.33% ab PRKCZ
TGA C 9 5 55.56% ab PRKCZ
TGA T 9 3 33.33% ab PRKCZ
TGA C 5 2 40.00% ab PRKCZ
TGA T 4 3 75.00% ab PRKCZ

我使用链接中的命令 How to Add Column with Percentage

awk 'NR==FNR{a = a + $2;next} {c = ($2/a)*100;print $1,$2,c }' file 文件

但它只返回三列而不是其余数据。输出如下

Ref_count   Alt_Count   0
2 2 0.00968429
6 6 0.0290529
8 7 0.033895
9 3 0.0145264
9 3 0.0145264
9 3 0.0145264
9 5 0.0242107
9 3 0.0145264
5 2 0.00968429
4 3 0.0145264

最佳答案

使用column 来对齐列:

$ awk 'BEGIN{FS=OFS="\t"}NR>1{$5=sprintf("%.2f%",$4/$3*100 )}1' file | column -t -s $'\t'
Ref Alt Ref_count Alt_Count Per (%) Func Ge
TGA T 2 2 100.00% ab PRKCZ
TGA c 6 6 100.00% ab PRKCZ
TGA C 8 7 87.50% ab PRKCZ
TGA T 9 3 33.33% ab PRKCZ
TGA C 9 3 33.33% ab PRKCZ
TGA T 9 3 33.33% ab PRKCZ
TGA C 9 5 55.56% ab PRKCZ
TGA T 9 3 33.33% ab PRKCZ
TGA C 5 2 40.00% ab PRKCZ
TGA T 4 3 75.00% ab PRKCZ

解释:

awk '
BEGIN { FS=OFS="\t" } # have and keep tab as field delimiter
NR>1 { # dont process header line
$5=sprintf("%.2f%%",$4/$3*100 ) # use sprintf to control decimals
}1' file

关于awk - 将百分比添加到制表符分隔文本中的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50265959/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com