Hello, I have the following very simple code:
library("dplyr")
I have the following data frame:
cars = data.frame(
brand = c("Ford", "Mercedes Benz", "Honda", "Ford", "Honda"),
color = c("Grey", "Black", "Blue", "Red", "Blue")
)
cars
## brand color
## 1 Ford Grey
## 2 Mercedes Benz Black
## 3 Honda Blue
## 4 Ford Red
## 5 Honda Blue
Also, I have the following mapping_car_country
:
mapping_car_country = data.frame(
brand = c("Ford", "Mercedes Benz", "Honda"),
country = c("USA", "Germany", "Japan")
)
mapping_car_country
## brand country
## 1 Ford USA
## 2 Mercedes Benz Germany
## 3 Honda Japan
My goal is: mutate data frame: cars
by adding a new column: country
accordingly with the mapping: mapping_car_country
.
I tried the following which is not correct, but probably it is an starting point:
# hardcoding "Ford" where it should be the brand on data frame: `cars`
# I need to get a reference to the outer brand somehow
cars = cars %>% mutate(country = (mapping_car_country %>% dplyr::filter(brand == "Ford"))[["country"]])
cars
## brand color country
## 1 Ford Grey USA
## 2 Mercedes Benz Black USA
## 3 Honda Blue USA
## 4 Ford Red USA
## 5 Honda Blue USA
Thanks!