R 查找其他数据帧中的匹配值和返回ID

R 查找其他数据帧中的匹配值和返回ID,r,lookup-tables,grepl,R,Lookup Tables,Grepl,我在R中有一个包含动物之间关系的数据框(关系): animal1 | animal2 | relationship dog cat friendly cat dog amicable pig goose mean 我有另一个数据框(动物)包含每种动物的信息: id | animal | count 1 dog 2 2 cat 5 3 pig 1

我在R中有一个包含动物之间关系的数据框(关系):

animal1 | animal2 | relationship  
dog       cat       friendly
cat       dog       amicable
pig       goose     mean
我有另一个数据框(动物)包含每种动物的信息:

id | animal | count   
1   dog       2      
2   cat       5       
3   pig       1     
4   goose     2
我想用第二个数据帧中的动物ID值替换第一个数据帧中的动物,即

animal1 | animal2 | relationship  
1       | 2       | friendly
2       | 1       | amicable
3       | 4       | mean
我该怎么做?到目前为止,我能够使用grepl对单个项目执行此操作,即

which(grepl(relationship$animal1[3],animal$id)) >>>> 2

如何在整个关系数据框中应用此选项,并用结果替换animal1/animal2列?

这里有一个使用
tidyverse
的选项。我们
收集
数据为“长”格式,
左连接
第二个数据集,将“动物”列更改为“id”和
扩散
格式

library(tidyverse)
gather(df1, key, animal, animal1:animal2) %>%
        left_join(df2[-3]) %>% 
        mutate(animal = id) %>% 
        select(-id)  %>% 
        spread(key, animal) %>%
        select(names(df1))

或者另一个不在
base R
中进行重塑的选项是循环前两列,将
与'df2'的'animal column'进行匹配,并获得相应的'id',将其分配回感兴趣的列

df1[1:2] <- lapply(df1[1:2], function(x) df2$id[match(x, df2$animal)])
df1
#   animal1 animal2 relationship
#1       1       2     friendly
#2       2       1     amicable
#3       3       4         mean

感谢@akrun提供的多个选项。我用了lapply,这个效果很好!
df1 %>% 
    mutate_at(vars(matches("animal")), funs(df2$id[match(., df2$animal)]))