【问题标题】:convert factor to numeric in bash在bash中将因子转换为数字
【发布时间】:2015-10-05 14:22:34
【问题描述】:

在 bash 中将因子向量(并非所有级别都是唯一的)转换为数字向量的最有效方法是什么?数值向量中的值无关紧要,只要每个值代表因子的唯一级别。

为了说明,这将是 R 等价于我想在 bash 中做的事情:

数字

即:

因素

AV1019A
ABG1787
AV1019A
B77hhA
B77hhA

数字

1
2
1
3
3

非常感谢。

【问题讨论】:

  • 尝试添加一些示例以使其清晰。
  • “数值向量中的值无关紧要,只要每个值代表因子的唯一级别”——哈希值如何?没有内置 bash,但只需调用您最喜欢的哈希器即可。 echo AV1019A | sha1sumecho AV1019A | sum.
  • 在这种情况下什么是因素???

标签: bash numeric-conversion


【解决方案1】:

这很可能不是最有效的,但也许可以开始。

#!/bin/bash

input_data=$( mktemp ) 
map_file=$( mktemp )

# your example written to a file 
echo -e "AV1019A\nABG1787\nAV1019A\nB77hhA\nB77hhA" >> $input_data 

# create a map <numeric, factor> and write to file
idx=0
for factor in $( cat $input_data | sort -u )
do 
    echo $idx $factor
    let idx=$idx+1
done > $map_file 

# go through your file again and replace values with keys 
while read line
do 
    key=$( cat $map_file | grep -e ".* ${line}$" | awk '{print $1}' )
    echo $key
done < $input_data 

# cleanup 
rm -f $input_data $map_file

我最初想使用关​​联数组,但它只是 bash 4+ 的一个功能,在这里和那里都不可用。如果你有 bash 4,那么你就少了一个文件,这显然更有效。

#!/bin/bash

# your example written to a file 
input_data=$( mktemp )
echo -e "AV1019A\nABG1787\nAV1019A\nB77hhA\nB77hhA" >> $input_data 

# declare an array 
declare -a factor_map=($( cat $input_data | sort -u | tr "\n" " " ))

# go through your file replace values with keys 
while read line
do 
    echo ${factor_map[@]/$line//} | cut -d/ -f1 | wc -w | tr -d ' '
done < $input_data 

# cleanup 
rm -f $input_data

【讨论】:

    猜你喜欢
    • 2015-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-06
    • 1970-01-01
    • 2017-09-30
    • 1970-01-01
    相关资源
    最近更新 更多