2015-10-05 69 views
0

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

为了说明,这将是R相当于什么我想在bash的事:

数字< -seq_along(水平(因素))[因素]

即:

因素

AV1019A
ABG1787
AV1019A
B77hhA
B77hhA

数字

非常感谢。

+2

尝试添加一些例子来说清楚。 – anubhava

+0

“只要每个数字表示一个唯一的因子水平,数字向量中的值就不重要了” - 散列怎么样?没有bash内建的,只是呼叫你最喜欢的hasher。 '回声AV1019A | sha1sum'或'echo AV1019A | sum'。 –

+2

在这种情况下什么是_factor_? –

回答

2

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

#!/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