为值分配唯一键,然后合并文件

时间:2015-12-06 13:22:17

标签: r

我想为文件中存在的值(名称)分配唯一的数字键。 例如, 文件名:abc和内容

Nathaniel
John
Penny
Vicky
Sam
Sid

然后,应该生成一个新文件,如

V1  V2
0   Nathaniel
1   John
2   Penny
3   Vicky
4   Sam
5   Sid

我该怎么办? 此外,还有一个像

这样的文件
V1           V2
Nathaniel    Penny
John         Sam
Penny       John
Vicky      Sid
Sam        John

现在,我必须根据之前指定的值将其转换为数字文件。 因此,新文件应为:

V1    V2
 0    2
 1    4
 2    1
 3    5
 4    1

我怎样才能实现它? 请帮忙。

1 个答案:

答案 0 :(得分:1)

这里有一个没有merge的解决方案。实际上你在这里尝试做的是用整数“重新编码”变量。想法是将它们转换为factor然后使用{{1} }。

首先我读了你的第一个向量,以便稍后将它作为因子级别使用:

as.integer

然后我将此向量用作级别因子。

## If you read values from a file
## change text= by file=
xx <- read.table(text='Nathaniel
John
           Penny
           Vicky
           Sam
           Sid')

我在这里创建## intermediate small function that transform character to integers ## Note I assume that xx$V1 don't have duplicate to_integer <- function(x) as.integer(factor(x,levels=xx$V1,ord=TRUE))-1 ## since we code the 2 vectors using same levels transform(tab2, V3= to_integer(V1),V4=to_integer(V2)) # V1 V2 V3 V4 # 1 Nathaniel Penny 0 2 # 2 John Sam 1 4 # 3 Penny John 2 1 # 4 Vicky Sid 3 5 # 5 Sam John 4 1 使用:

tab2