R - Excel VLOOKUP equivalent - search, replace

I looked almost everywhere and cannot find the answer to this; R is the equivalent of VLOOKUP in Excel. VLOOKUP allows me to search for a specific value in a column and apply it to every row of my data frame.

In this case, I want to find the country in which a particular city is located (from the database), and return the name of the country to 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 I want to find the country where these cities are located (replace NA), based on the above db:

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

I do not know how to do this on R.

+4
source share
2 answers

You do a join , which in R is done using a function merge

merge(db, df)

dplyr :

library(dplyr)
inner_join(db, df)

, , ( -, . ?left_join ):

left_join(db, df)
+6

:

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

Source: https://habr.com/ru/post/1543049/


All Articles