其他数据框中的查找匹配值和返回ID [重复]

问题描述 投票:1回答: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

如何在整个关系数据框架中应用此项并将结果替换为动物1 /动物2列?

r lookup-tables grepl
1个回答
1
投票

这是一个使用tidyverse的选项。我们gather将数据转换为'long'格式,left_join使用第二个数据集,将'animal'列改为'id',将spread改为'wide'格式

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'的'动物列'做match并获得相应的'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

或者与dplyr类似的方法

df1 %>% 
    mutate_at(vars(matches("animal")), funs(df2$id[match(., df2$animal)]))
© www.soinside.com 2019 - 2024. All rights reserved.