R - Excel VLOOKUP 等效 - 查找,替换 [英] R - Excel VLOOKUP equivalent - Lookup, replace

查看:35
本文介绍了R - Excel VLOOKUP 等效 - 查找,替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我几乎到处都找遍了,但找不到答案;R 相当于 Excel 上的 VLOOKUP.VLOOKUP 允许我在整个列中查找特定值并将其应用于数据框的每一行.

I have looked pretty much everywhere and cannot find the answer to this; R equivalent of VLOOKUP on Excel. VLOOKUP allows me to look up for a specific value throughout a column and apply it to each row of my data frame.

在这种情况下,我想查找特定城市所在的国家/地区(从数据库中)并在新列中返回该国家/地区的名称.

In this case I want to find the country a particular city is in (from a database) and return the name of the country in a new column.

所以我有这个数据库:

countries <- c("UK", "US", "RUS")
cities <- c("LDN", "NY", "MOSC")
db <- cbind(countries, cities)
db
      countries cities
[1,] "UK"      "LDN" 
[2,] "US"      "NY"  
[3,] "RUS"     "MOSC"

并想根据上面的数据库找到这些城市所在的国家(替换 NA):

And want to find the country those cities are in (replace NA) based on the db above:

df
     countries cities
[1,]   NA      "LDN" 
[2,]   NA      "NY"  
[3,]   NA     "MOSC"

我完全不知道如何在 R 上解决这个问题.

I have absolutely no idea how to go about this on R.

推荐答案

您正在执行 join 在 R 中使用 merge

merge(db, df)

使用 dplyr 包允许更自然的动词:

Using the dplyr package allows more natural verbs:

library(dplyr)
inner_join(db, df)

或者(如果您希望显示不匹配的内容;请参阅 ?left_join 了解更多信息):

or perhaps (if you want non-matches to be shown; see ?left_join for further information):

left_join(db, df)

这篇关于R - Excel VLOOKUP 等效 - 查找,替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆