字符匹配时如何获取id

How to get the id when the character matches

我将得到一个输入表单 df1,如果名称与 df 匹配,我需要获得相应的 ID ex(健康意味着 2)谁能帮助我了解如何捕获该 ID

df <- data.frame(id = c(1,2,3,4), B = c('agri','health','edu','energy'))
    
df1 <- data.frame(name = c('agri','health','edu','energy')) 

如果您对所有比赛感兴趣:

df$id[match(df1$name, df$B)]

也许您想将相应的 ID 添加到您的 df1 数据中?

那么你可以这样做:

df1$new_id <- df$id[match(df1$name, df$B)]

给出:

    name new_id
1   agri      1
2 health      2
3    edu      3
4 energy      4