R - Excel VLOOKUP equivalent - Lookup, replace [duplicate]

不想你离开。 提交于 2019-12-03 13:33:08

问题


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.

So I have this database:

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"

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"

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


回答1:


You are performing a join which in R is performed using the function merge

merge(db, df)

Using the dplyr package allows more natural verbs:

library(dplyr)
inner_join(db, df)

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

left_join(db, df)



回答2:


Here's another approach:

library(qdapTools)
df[, 1] <- df[, 2] %l% db[, 2:1]


来源:https://stackoverflow.com/questions/24012636/r-excel-vlookup-equivalent-lookup-replace

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!