根据另一个数据帧中名称的行索引将名称转换为数据框中的数字

时间:2014-12-10 21:43:56

标签: r network-analysis

我有两个数据帧。一个是我的facebook朋友的名字,另一个是与sorce和目标列的链接。我想根据朋友数据框中该名称的行索引将链接数据框中的名称转换为数字。

朋友

               name
1    Andrewt Thomas
2     Robbie McCord
3 Mohammad Mojadidi
4       Andrew John
5     Professor Owk
6    Joseph Charles

链接

     source          target
1 Andrewt Thomas     Andrew John
2 Andrewt Thomas       James Zou
3  Robbie McCord         Bz Benz
4  Robbie McCord Yousef AL-alawi
5  Robbie McCord  Sherhan Asimov
6  Robbie McCord     Aigerim Aig

似乎微不足道,但我无法弄清楚。谢谢你的帮助。

2 个答案:

答案 0 :(得分:5)

只需使用简单的match

即可
links$source <- match(links$source, friends$name)
links
#   source          target
# 1      1     Andrew John
# 2      1       James Zou
# 3      2         Bz Benz
# 4      2 Yousef AL-alawi
# 5      2  Sherhan Asimov
# 6      2     Aigerim Aig

答案 1 :(得分:1)

这样的东西?

links$source <- vapply(links$source, function(x) which(friends$name == x), integer(1))

完整示例

links <- data.frame(source = c("John", "John", "Alice"), target = c("Jimmy", "Al", "Chris"))
links$source <- vapply(links$source, function(x) which(friends$name == x), integer(1))
links$source
[1] 3 3 2